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
e5f367ec6f030c577f92a8d84d6a9a8d0dca987b
a79fbaa0083667aa86d044c588874774ece57f28
/api_arv/tools/calibration/artk_hmd/src/.svn/text-base/main.cpp.svn-base
f5592194115b7c31b7fb0d652d5149237c380bfa
[]
no_license
VB6Hobbyst7/RVProject
c04b88f27ac8a84f912ec86191574d111cd8fc6c
0e2461da5ae347fb5707d7e8b1ba247a24bd4a9a
refs/heads/master
2021-12-02T07:29:24.001171
2011-01-28T17:04:46
2011-01-28T17:04:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,683
/* --------------------------------------------------------------------------- * Copyright (C) 2004 ENSIMAG, INPG. * The distribution policy is describe on the Copyright.txt furnish * with this library. */ /*! --------------------------------------------------------------------------- * * file ARVARTHMDCalib.C * author Raphael Grasset * version 1.0 * date 16/04/2004 * purpose calibrate transformation between art tracking and eye in HMD. */ #include <ApiArv/Camera.h> #include <ApiArv/Tracker.h> #include <GL/gl.h> #include <GL/glut.h> #include <iostream> #include <fstream> using namespace arv; Camera *camera; Tracker *tracker; #define CALIB_POS1_NUM 5 #define CALIB_POS2_NUM 2 static double calib_pos[CALIB_POS1_NUM][2] = { { 160, 120 }, { 480, 120 }, { 320, 240 }, { 160, 360 }, { 480, 360 } }; static ARParam hmd_param; static double calib_pos2d[CALIB_POS1_NUM][CALIB_POS2_NUM][2]; static double calib_pos3d[CALIB_POS1_NUM][CALIB_POS2_NUM][3]; bool target_visible; double patt_trans[3][4]; int targetmesureid; int mesureid; bool calibrate_mode; bool seethrough_mode; double gl_calib[16]; //translate ART struct to openGL matrix struct static void ARTCalibToGL( double cparam[3][4], int width, int height, double gnear, double gfar, double m[16] ) { double icpara[3][4]; double trans[3][4]; double p[3][3], q[4][4]; int i, j; if ( arParamDecompMat(cparam, icpara, trans) < 0 ) { std::cerr << "ERROR->ARTCALIBTOGL:gConvGLcpara: Parameter error!!" << std::endl; exit(0); } for ( i = 0; i < 3; i++ ) { for ( j = 0; j < 3; j++ ) { p[i][j] = icpara[i][j] / icpara[2][2]; } } q[0][0] = (2.0 * p[0][0] / width); q[0][1] = (2.0 * p[0][1] / width); q[0][2] = ((2.0 * p[0][2] / width) - 1.0); q[0][3] = 0.0; q[1][0] = 0.0; q[1][1] = (2.0 * p[1][1] / height); q[1][2] = ((2.0 * p[1][2] / height) - 1.0); q[1][3] = 0.0; q[2][0] = 0.0; q[2][1] = 0.0; q[2][2] = (gfar + gnear) / (gfar - gnear); q[2][3] = -2.0 * gfar * gnear / (gfar - gnear); q[3][0] = 0.0; q[3][1] = 0.0; q[3][2] = 1.0; q[3][3] = 0.0; for ( i = 0; i < 4; i++ ) { for ( j = 0; j < 3; j++ ) { m[i + j*4] = q[i][0] * trans[0][j] + q[i][1] * trans[1][j] + q[i][2] * trans[2][j]; } m[i + 3*4] = q[i][0] * trans[0][3] + q[i][1] * trans[1][3] + q[i][2] * trans[2][3] + q[i][3]; } } //display line for align marker void displayTarget(double x, double y) { glLineWidth( 3.0 ); if (mesureid % CALIB_POS2_NUM == 0) glColor3f( 1.0, 1.0, 1.0 ); else glColor3f( 1.0, 0.0, 0.0 ); glBegin(GL_LINES); glVertex2f(x, 0.); glVertex2f(x, 480.); glEnd(); glBegin(GL_LINES); glVertex2f(0., y); glVertex2f(640., y); glEnd(); } //compute the calibration void computeCalibration() { //init parameters struct hmd_param.xsize = 640; hmd_param.ysize = 480; hmd_param.dist_factor[0] = 320; hmd_param.dist_factor[1] = 240; hmd_param.dist_factor[2] = 0.0; hmd_param.dist_factor[3] = 1.0; //resolve AX=B, with A 3D points, B 2D points and X transformation matrix if ( arParamGet( (double (*)[3])calib_pos3d, (double (*)[2])calib_pos2d, CALIB_POS1_NUM*CALIB_POS2_NUM, hmd_param.mat) < 0 ) { std::cerr << "ERROR->COMPUTECALIBRATION : can't find calibration matrix !! (bad measured values ?)" << std::endl; } else { std::cout << "camera calibrate.. OK" << std::endl; //transform result to GL matrix ARTCalibToGL(hmd_param.mat, hmd_param.xsize, hmd_param.ysize, 100., 100000., gl_calib); //save matrix std::ofstream artfile; artfile.open("output/arthmd.calib"); for (int i = 0;i < 16;i++) artfile << gl_calib[i] << std::endl; artfile.close(); std::cout << "parameters saves in output/arthmd.calib" << std::endl; //reset all for new calibration targetmesureid = 0; mesureid = 0; calibrate_mode = false; } } void mouseEvent(int button, int state, int /*x*/, int /*y*/) { if ( button == GLUT_LEFT_BUTTON && state == GLUT_DOWN ) { if (target_visible) { std::cout << "new measure.." << std::endl; // fprintf(stderr,"%f %f %f, %f %f\n",patt_trans[0][3],patt_trans[1][3],patt_trans[2][3],patt_trans[3][3],calib_pos[targetmesureid][0],calib_pos[targetmesureid][1]); calib_pos3d[targetmesureid][mesureid][0] = patt_trans[0][3]; calib_pos3d[targetmesureid][mesureid][1] = patt_trans[1][3]; calib_pos3d[targetmesureid][mesureid][2] = patt_trans[2][3]; calib_pos2d[targetmesureid][mesureid][0] = calib_pos[targetmesureid][0]; calib_pos2d[targetmesureid][mesureid][1] = calib_pos[targetmesureid][1]; mesureid++; if ( mesureid == CALIB_POS2_NUM ) { // calibrate with next value targetmesureid++; mesureid = 0; std::cout << "new position.." << std::endl; } if ( targetmesureid == CALIB_POS1_NUM ) { // that's finished : compute calibration std::cerr << "calibrate.." << std::endl; computeCalibration(); } } // otherwise do nothing } if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN ) calibrate_mode = !calibrate_mode; if (button == GLUT_MIDDLE_BUTTON && state == GLUT_DOWN ) seethrough_mode = !seethrough_mode; } void drawScene(double projection[16], double model[16]) { GLfloat mat_ambient[] = {0.0, 0.0, 1.0, 1.0}; GLfloat mat_flash[] = {0.0, 0.0, 1.0, 1.0}; GLfloat mat_flash_shiny[] = {50.0}; GLfloat light_position[] = {100.0, -200.0, 200.0, 0.0}; GLfloat ambi[] = {0.1, 0.1, 0.1, 0.1}; GLfloat lightZeroColor[] = {0.9, 0.9, 0.9, 0.1}; glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); //setup with ART tracking glMatrixMode(GL_PROJECTION); glLoadIdentity(); glLoadMatrixd(projection); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glLoadMatrixd(model); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightfv(GL_LIGHT0, GL_AMBIENT, ambi); glLightfv(GL_LIGHT0, GL_DIFFUSE, lightZeroColor); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_flash); glMaterialfv(GL_FRONT, GL_SHININESS, mat_flash_shiny); glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMatrixMode(GL_MODELVIEW); //display base on marker glPushMatrix(); glScalef(1.1, 1.1, 0.02); glutSolidCube(80.0); glPopMatrix(); //put cube on marker glTranslatef( 0.0, 0.0, 40.0 ); glutSolidCube(80.0); } void display(void) { int sx, sy; GLfloat zoom; int xVideo, yVideo; xVideo = 640; yVideo = 480; zoom = 1.; sx = 0; sy = yVideo - 1; char*image = camera->getImage(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho( -0.5, xVideo - 0.5, -0.5, yVideo - 0.5, -1.0, 1.0); glViewport(0, 0, xVideo, yVideo); glDisable( GL_LIGHTING ); glDisable( GL_DEPTH_TEST ); glDepthMask(GL_FALSE); // // copy video image with draw pixels glPixelZoom( zoom, -zoom); glRasterPos3i( sx, sy, 0 ); if (!seethrough_mode) glDrawPixels(xVideo, yVideo, GL_BGR, GL_UNSIGNED_BYTE, image ); glDepthMask(GL_TRUE); camera->update(); tracker->update(image); target_visible = 0; if (tracker->isMarkerVisible(0)) { target_visible = 1; tracker->getPos(0, patt_trans); double gl_para[16]; tracker->getGLModelMatrix(0, gl_para); if (calibrate_mode) displayTarget(calib_pos[targetmesureid][0], calib_pos[targetmesureid][1]); else { arFittingMode = AR_FITTING_TO_IDEAL; drawScene(gl_calib, gl_para); } } glutSwapBuffers(); } void keyboard(unsigned char key, int /*x*/, int /*y*/) { if (key == 27) { fprintf(stderr, "BYE\n"); exit(0); } } int main(int argc, char* argv[]) { //init camera camera = new Camera(1); //USB camera by default camera->init(); int x, y; camera->getSize(x, y); //init art tracker = new Tracker("data/calibart.dat"); //calibrate pattern tracker->init(); tracker->setThreshold(100); //init calibration parameters targetmesureid = 0; mesureid = 0; calibrate_mode = true; seethrough_mode = true; hmd_param.xsize = 640; hmd_param.ysize = 480; hmd_param.dist_factor[0] = 320; hmd_param.dist_factor[1] = 240; hmd_param.dist_factor[2] = 0.0; hmd_param.dist_factor[3] = 1.0; hmd_param.mat[0][0] = 745.28133; hmd_param.mat[0][1] = -115.01106; hmd_param.mat[0][2] = 125.39974; hmd_param.mat[0][3] = 57978.82635; hmd_param.mat[1][0] = -52.95057; hmd_param.mat[1][1] = -742.93424; hmd_param.mat[1][2] = 21.78003; hmd_param.mat[1][3] = 71782.45592; hmd_param.mat[2][0] = 0.02867; hmd_param.mat[2][1] = -0.11825; hmd_param.mat[2][2] = 0.42484 ; hmd_param.mat[2][3] = 100.00000; ARTCalibToGL(hmd_param.mat, hmd_param.xsize, hmd_param.ysize, 10., 1000., gl_calib); //init viewer glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); glutInitWindowPosition(0, 0); glutInitWindowSize(640, 480); glutCreateWindow("ARV Live Video (in openGL)"); glutDisplayFunc(display); glutIdleFunc(display); glutMouseFunc(mouseEvent); glutKeyboardFunc(keyboard); glutFullScreen(); //start camera : camera->start(); std::cout << "ARVARTHMDCalib" << std::endl; std::cout << "to calibrate :" << std::endl; std::cout << "1. Put the HMD on your head" << std::endl; std::cout << "2. Press MIDDLE mouse button, to check if the camera and the eye have 'similar' view (except scale and some translation error). Press at new right button" << std::endl; std::cout << "3. Take the calibration tool (with two white cubes marker)" << std::endl; std::cout << "4. Align the center between 2 virtual white cubes with the intersection of two lines. Do it each time at short distance and at long distance (maximum arm reach). Press LEFT mouse button when the registration is OK. If the two lines disappear, the pattern is not visible by the camera (change orientation, or lighting condition)." << std::endl; std::cout << "4. Repeat this sequence 5 times (left bottom, right bottom, center, left up, right up" << std::endl; std::cout << "5. A cube must appear above the marker : check that registration is good" << std::endl; std::cout << "6. If not press RIGHT mouse button for retry" << std::endl; std::cout << "5. Press ESCAPE on keyboard when you are satisfy" << std::endl; glutMainLoop(); return 0; }
[ "meuh@Rosalie.(none)" ]
[ [ [ 1, 362 ] ] ]
88a49c3c4a207cdbbae7b56c669c4c4a7530b0e8
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.2/bctestuniteditor/src/bctestuniteditorcontainer.cpp
cd5211a10f04f802c3e3c69ffb8151ec2bd8ebfe
[]
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
3,618
cpp
/* * Copyright (c) 2007 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: container * */ #include "bctestuniteditorcontainer.h" #define KAknAtListGray TRgb(0xaaaaaa) // ======== MEMBER FUNCTIONS ======== // --------------------------------------------------------------------------- // C++ default Constructor // --------------------------------------------------------------------------- // CBCTestUnitEditorContainer::CBCTestUnitEditorContainer() { } // --------------------------------------------------------------------------- // Destructor // --------------------------------------------------------------------------- // CBCTestUnitEditorContainer::~CBCTestUnitEditorContainer() { ResetControl(); } // --------------------------------------------------------------------------- // Symbian 2nd Constructor // --------------------------------------------------------------------------- // void CBCTestUnitEditorContainer::ConstructL( const TRect& aRect ) { CreateWindowL(); SetRect( aRect ); ActivateL(); } // ---------------------------------------------------------------------------- // CBCTestUnitEditorContainer::Draw // Fills the window's rectangle. // ---------------------------------------------------------------------------- // void CBCTestUnitEditorContainer::Draw( const TRect& aRect ) const { CWindowGc& gc = SystemGc(); gc.SetPenStyle( CGraphicsContext::ENullPen ); gc.SetBrushColor( KAknAtListGray ); gc.SetBrushStyle( CGraphicsContext::ESolidBrush ); gc.DrawRect( aRect ); } // --------------------------------------------------------------------------- // CBCTestUnitEditorContainer::CountComponentControls // --------------------------------------------------------------------------- // TInt CBCTestUnitEditorContainer::CountComponentControls() const { if ( iControl ) { return 1; } else { return 0; } } // --------------------------------------------------------------------------- // CBCTestUnitEditorContainer::ComponentControl // --------------------------------------------------------------------------- // CCoeControl* CBCTestUnitEditorContainer::ComponentControl( TInt ) const { return iControl; } // --------------------------------------------------------------------------- // CBCTestUnitEditorContainer::SetControl // --------------------------------------------------------------------------- // void CBCTestUnitEditorContainer::SetControl( CCoeControl* aControl ) { iControl = aControl; if ( iControl ) { // You can change the position and size iControl->SetExtent( Rect().iTl, Rect().Size() ); iControl->ActivateL(); DrawNow(); } } // --------------------------------------------------------------------------- // CBCTestUnitEditorContainer::ResetControl // --------------------------------------------------------------------------- // void CBCTestUnitEditorContainer::ResetControl() { delete iControl; iControl = NULL; }
[ "none@none" ]
[ [ [ 1, 116 ] ] ]
1ddfb7bb0d5c4edd651e2a622b00efa2f53a5316
6630a81baef8700f48314901e2d39141334a10b7
/1.4/Testing/Cxx/swWxGuiTesting/CppGuiTest/swCRCaptureTest.cpp
6e4d51bababb3ca0e32548bed1e91e2c8c776fac
[]
no_license
jralls/wxGuiTesting
a1c0bed0b0f5f541cc600a3821def561386e461e
6b6e59e42cfe5b1ac9bca02fbc996148053c5699
refs/heads/master
2021-01-10T19:50:36.388929
2009-03-24T20:22:11
2009-03-26T18:51:24
623,722
1
0
null
null
null
null
ISO-8859-1
C++
false
false
12,995
cpp
/////////////////////////////////////////////////////////////////////////////// // Name: swWxGuiTesting/CppGuiTest/swCRCaptureTest.cpp // Author: Reinhold Füreder // Created: 2004 // Copyright: (c) 2005 Reinhold Füreder // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// #ifdef __GNUG__ #pragma implementation "swCRCaptureTest.h" #endif #include "swCRCaptureTest.h" #include "wx/xrc/xmlres.h" #include "wx/frame.h" #include "wx/treectrl.h" #include "swWxGuiTestHelper.h" #include "swWxGuiTestEventSimulationHelper.h" #include "swWxGuiTestTimedDialogEnder.h" #include "swWxGuiTestTempInteractive.h" #include "swCRCapture.h" #include "swConfigManager.h" #include "swConfig.h" // Only to make C&R demonstrations easier: #include "wx/notebook.h" #include "swSpinCtrlDouble.h" #include "swTreeCtrl.h" using sw::SpinCtrlDouble; namespace swTst { // Register test suite with special name in order to be identifiable as test // which must be run after GUI part of wxWidgets library is initialised: CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CRCaptureTest, "WxGuiTest" ); void CRCaptureTest::setUp () { wxXmlResource::Get()->InitAllHandlers(); wxXmlResource::Get()->Load ("../../../Cxx/swWxGuiTesting/CppGuiTest/EvtSimHlpTest_wdr.xrc"); wxFrame *frame = new wxFrame (NULL, -1, "EvtSimHlpFrame"); wxMenuBar *menuBar = wxXmlResource::Get ()->LoadMenuBar (wxT("MenuBar")); wxASSERT (menuBar != NULL); frame->SetMenuBar (menuBar); wxBoxSizer *topsizer = new wxBoxSizer (wxVERTICAL); wxPanel *panel = wxXmlResource::Get ()->LoadPanel (frame, "EvtSimHlpTestPanel"); wxASSERT (panel != NULL); // Include the unknown double spin control: sw::SpinCtrlDouble *spinCtrl = new sw::SpinCtrlDouble (frame, -1, "", wxDefaultPosition, wxSize (80, 21), wxNO_BORDER, 0.00000, 9999.99999, 0.5, 0.1); spinCtrl->SetDigits (5, false); wxXmlResource::Get ()->AttachUnknownControl ("SpinCtrlDbl", spinCtrl, frame); wxTreeCtrl *treeCtrl = XRCCTRL (*frame, "TreeCtrl", wxTreeCtrl); wxTreeItemId root = treeCtrl->AddRoot ("Root"); wxTreeItemId item = treeCtrl->AppendItem (root, "item"); wxTreeItemId item2 = treeCtrl->AppendItem (root, "item2"); topsizer->Add (panel, 1, wxGROW | wxADJUST_MINSIZE, 0); topsizer->SetSizeHints (frame); frame->SetSizer (topsizer); frame->Show (); wxTheApp->SetTopWindow (frame); WxGuiTestHelper::Show (frame, true, false); WxGuiTestHelper::FlushEventQueue (); wxString xrcDir = "../../../TestData/xrc/CaptureTest/"; sw::Config *configInit = new sw::Config (); configInit->SetResourceDir (xrcDir); sw::ConfigManager::SetInstance (configInit); } void CRCaptureTest::tearDown () { sw::ConfigManager::SetInstance (NULL); wxWindow *topWdw = wxTheApp->GetTopWindow (); wxTheApp->SetTopWindow (NULL); topWdw->Hide (); } void CRCaptureTest::testCapture () { swTst::WxGuiTestTempInteractive interactive; /* CPPUNIT_ASSERT_MESSAGE ("Application top window invalid", wxTheApp-> GetTopWindow () != NULL); wxFrame *topFrame = dynamic_cast< wxFrame * >(wxTheApp->GetTopWindow ()); CPPUNIT_ASSERT_MESSAGE ("Top window is not a frame", topFrame != NULL); wxMenuBar *menuBar = topFrame->GetMenuBar (); CPPUNIT_ASSERT_MESSAGE ("Menubar not found", menuBar != NULL); interactive.ShowCurrentGui (); int checkableMenuItemMenuItemId = menuBar->FindMenuItem (_("Menu"), _( "CheckableMenuItem")); CPPUNIT_ASSERT_MESSAGE ("Menu item ID 'CheckableMenuItem' not found", checkableMenuItemMenuItemId != wxNOT_FOUND); wxMenuItem *checkableMenuItemMenuItem = menuBar->FindItem ( checkableMenuItemMenuItemId); CPPUNIT_ASSERT_MESSAGE ("Menu item 'CheckableMenuItem' not found", checkableMenuItemMenuItem != NULL); // Check if checkable menu item is not already checked? // if (!checkableMenuItemMenuItem->IsChecked ()) { ... swTst::WxGuiTestEventSimulationHelper::SelectAndCheckMenuItem ( checkableMenuItemMenuItemId, topFrame); swTst::WxGuiTestHelper::FlushEventQueue (); interactive.ShowCurrentGui (); wxWindow *evtSimHlpTestPanel = wxWindow::FindWindowByName ( "EvtSimHlpTestPanel"); CPPUNIT_ASSERT_MESSAGE ("Container window for button 'Button' not found", evtSimHlpTestPanel != NULL); wxWindow *textCtrlWdw = evtSimHlpTestPanel->FindWindow (XRCID("TextCtrl")); CPPUNIT_ASSERT_MESSAGE ("Window for text control 'TextCtrl' not found", textCtrlWdw != NULL); wxTextCtrl *textCtrl = wxDynamicCast (textCtrlWdw, wxTextCtrl); CPPUNIT_ASSERT_MESSAGE ("Converting window for text control 'TextCtrl' " "failed", textCtrl != NULL); swTst::WxGuiTestEventSimulationHelper::SetTextCtrlValue (textCtrl, "oh-la-la"); swTst::WxGuiTestHelper::FlushEventQueue (); interactive.ShowCurrentGui (); wxWindow *spinCtrlDblWdw = evtSimHlpTestPanel->FindWindow (XRCID( "SpinCtrlDbl")); CPPUNIT_ASSERT_MESSAGE ("Window for spin control 'SpinCtrlDbl' not found", spinCtrlDblWdw != NULL); sw::SpinCtrlDouble *spinCtrlDbl = wxDynamicCast (spinCtrlDblWdw, SpinCtrlDouble); CPPUNIT_ASSERT_MESSAGE ("Converting window for spin control 'SpinCtrlDbl' " "failed", spinCtrlDbl != NULL); swTst::WxGuiTestEventSimulationHelper::SetSpinCtrlDblValue (spinCtrlDbl, 0.6); swTst::WxGuiTestHelper::FlushEventQueue (); wxWindow *treeCtrlWdw = evtSimHlpTestPanel->FindWindow (XRCID("TreeCtrl")); CPPUNIT_ASSERT_MESSAGE ("Window for tree control 'TreeCtrl' not found", treeCtrlWdw != NULL); wxTreeCtrl *treeCtrl = wxDynamicCast (treeCtrlWdw, wxTreeCtrl); CPPUNIT_ASSERT_MESSAGE ("Converting window for tree control 'TreeCtrl' " "failed", treeCtrl != NULL); wxTreeItemId rootId = treeCtrl->GetRootItem (); CPPUNIT_ASSERT_MESSAGE ("Tree control root item is invalid", rootId.IsOk ( )); swTst::WxGuiTestEventSimulationHelper::SelectTreeItem (rootId, treeCtrl); swTst::WxGuiTestHelper::FlushEventQueue (); wxWindow *treeCtrlWdw1 = evtSimHlpTestPanel->FindWindow (XRCID("TreeCtrl")); CPPUNIT_ASSERT_MESSAGE ("Window for tree control 'TreeCtrl' not found", treeCtrlWdw1 != NULL); wxTreeCtrl *treeCtrl1 = wxDynamicCast (treeCtrlWdw1, wxTreeCtrl); CPPUNIT_ASSERT_MESSAGE ("Converting window for tree control 'TreeCtrl' " "failed", treeCtrl1 != NULL); wxTreeItemId treeItemId1 = sw::TreeCtrl::GetNthChild (treeCtrl1, 1, rootId); CPPUNIT_ASSERT_MESSAGE ("Tree control item is invalid", treeItemId1.IsOk ( )); swTst::WxGuiTestEventSimulationHelper::SelectTreeItem (treeItemId1, treeCtrl1); swTst::WxGuiTestHelper::FlushEventQueue (); wxWindow *treeCtrlWdw2 = evtSimHlpTestPanel->FindWindow (XRCID("TreeCtrl")); CPPUNIT_ASSERT_MESSAGE ("Window for tree control 'TreeCtrl' not found", treeCtrlWdw2 != NULL); wxTreeCtrl *treeCtrl2 = wxDynamicCast (treeCtrlWdw2, wxTreeCtrl); CPPUNIT_ASSERT_MESSAGE ("Converting window for tree control 'TreeCtrl' " "failed", treeCtrl2 != NULL); treeCtrl2->Expand (rootId); wxTreeItemId treeItemId11 = sw::TreeCtrl::GetNthChild (treeCtrl2, 1, rootId); CPPUNIT_ASSERT_MESSAGE ("Tree control item is invalid", treeItemId11.IsOk ( )); swTst::WxGuiTestEventSimulationHelper::RightClickTreeItem (treeItemId11, treeCtrl2); swTst::WxGuiTestHelper::FlushEventQueue (); wxWindow *treeCtrlWdw3 = evtSimHlpTestPanel->FindWindow (XRCID("TreeCtrl")); CPPUNIT_ASSERT_MESSAGE ("Window for tree control 'TreeCtrl' not found", treeCtrlWdw3 != NULL); wxTreeCtrl *treeCtrl3 = wxDynamicCast (treeCtrlWdw3, wxTreeCtrl); CPPUNIT_ASSERT_MESSAGE ("Converting window for tree control 'TreeCtrl' " "failed", treeCtrl3 != NULL); wxTreeItemId treeItemId12 = sw::TreeCtrl::GetNthChild (treeCtrl3, 2, rootId); CPPUNIT_ASSERT_MESSAGE ("Tree control item is invalid", treeItemId12.IsOk ( )); swTst::WxGuiTestEventSimulationHelper::SelectTreeItem (treeItemId12, treeCtrl3); swTst::WxGuiTestHelper::FlushEventQueue (); wxWindow *notebookWdw = wxWindow::FindWindowByName ("Notebook"); CPPUNIT_ASSERT_MESSAGE ("Container window for notebook 'Notebook' not " "found", notebookWdw != NULL); wxNotebook *notebook = wxDynamicCast (notebookWdw, wxNotebook); CPPUNIT_ASSERT_MESSAGE ("Converting window for notebook 'Notebook' failed", notebook != NULL); const wxString notebookPageText (_("Page2")); int notebookPage = 0; while ((notebookPage < notebook->GetPageCount ()) && (notebook-> GetPageText (notebookPage) != notebookPageText)) { notebookPage++; } CPPUNIT_ASSERT_MESSAGE ("Page of notebook 'Notebook' not found", notebookPage < notebook->GetPageCount ()); swTst::WxGuiTestEventSimulationHelper::SelectNotebookPage (notebook, notebookPage); swTst::WxGuiTestHelper::FlushEventQueue (); wxWindow *choiceWdw = evtSimHlpTestPanel->FindWindow (XRCID("Choice")); CPPUNIT_ASSERT_MESSAGE ("Window for choice 'Choice' not found", choiceWdw != NULL); wxChoice *choice = wxDynamicCast (choiceWdw, wxChoice); CPPUNIT_ASSERT_MESSAGE ("Converting window for choice 'Choice' failed", choice != NULL); const wxString choiceSelectionText (_("Item")); int choiceSelection = choice->FindString (choiceSelectionText); swTst::WxGuiTestEventSimulationHelper::SelectChoiceItem (choice, choiceSelection); swTst::WxGuiTestHelper::FlushEventQueue (); wxWindow *checkboxWdw = evtSimHlpTestPanel->FindWindow (XRCID("Checkbox")); CPPUNIT_ASSERT_MESSAGE ("Window for check box 'Checkbox' not found", checkboxWdw != NULL); wxCheckBox *checkbox = wxDynamicCast (checkboxWdw, wxCheckBox); CPPUNIT_ASSERT_MESSAGE ("Converting window for check box 'Checkbox' " "failed", checkbox != NULL); swTst::WxGuiTestEventSimulationHelper::SetCheckboxState (checkbox, true); swTst::WxGuiTestHelper::FlushEventQueue (); wxWindow *radioBoxWdw = evtSimHlpTestPanel->FindWindow (XRCID("RadioBox")); CPPUNIT_ASSERT_MESSAGE ("Window for radio box 'RadioBox' not found", radioBoxWdw != NULL); wxRadioBox *radioBox = wxDynamicCast (radioBoxWdw, wxRadioBox); CPPUNIT_ASSERT_MESSAGE ("Converting window for radio box 'RadioBox' " "failed", radioBox != NULL); const wxString radioBoxSelectionText (_("Radio2")); int radioBoxSelection = radioBox->FindString (radioBoxSelectionText); swTst::WxGuiTestEventSimulationHelper::SelectRadioBoxItem (radioBox, radioBoxSelection); swTst::WxGuiTestHelper::FlushEventQueue (); wxWindow *sliderWdw = evtSimHlpTestPanel->FindWindow (XRCID("Slider")); CPPUNIT_ASSERT_MESSAGE ("Window for slider 'Slider' not found", sliderWdw != NULL); wxSlider *slider = wxDynamicCast (sliderWdw, wxSlider); CPPUNIT_ASSERT_MESSAGE ("Converting window for slider 'Slider' failed", slider != NULL); swTst::WxGuiTestEventSimulationHelper::SetSliderValue (slider, 27); swTst::WxGuiTestHelper::FlushEventQueue (); wxWindow *spinCtrlWdw = evtSimHlpTestPanel->FindWindow (XRCID("SpinCtrl")); CPPUNIT_ASSERT_MESSAGE ("Window for spin control 'SpinCtrl' not found", spinCtrlWdw != NULL); wxSpinCtrl *spinCtrl = wxDynamicCast (spinCtrlWdw, wxSpinCtrl); CPPUNIT_ASSERT_MESSAGE ("Converting window for spin control 'SpinCtrl' " "failed", spinCtrl != NULL); swTst::WxGuiTestEventSimulationHelper::SetSpinCtrlValue (spinCtrl, 1); swTst::WxGuiTestHelper::FlushEventQueue (); */ // Do bootstrap capturing: /* { wxApp *app = wxTheApp; wxASSERT (app != NULL); Tst::WxGuiTestApp *guiTestApp = dynamic_cast< Tst::WxGuiTestApp * >(app); wxASSERT (guiTestApp != NULL); guiTestApp->SetEventFilter (Tst::CREventCaptureManager::GetInstance ()); Tst::CRCapture *capture = new Tst::CRCapture (); try { capture->Capture (__FILE__, __LINE__); } catch (...) { guiTestApp->SetEventFilter (NULL); throw; } guiTestApp->SetEventFilter (NULL); delete capture; Tst::CRCppEmitter::Destroy (); } */ // Or use easier macro: CAPTURE interactive.ShowCurrentGui (); // Using the {...} notation we can have several CAPTUREs in one method: //CAPTURE } } // End namespace swTst
[ "john@64288482-8357-404e-ad65-de92a562ee98" ]
[ [ [ 1, 316 ] ] ]
263668ee053c46850f647bbccccd1470938ae110
f6529b63d418f7d0563d33e817c4c3f6ec6c618d
/source/gui/text.cpp
22a736f0a755e2a0151abd40f360c8a44732c34a
[]
no_license
Captnoord/Wodeflow
b087659303bc4e6d7360714357167701a2f1e8da
5c8d6cf837aee74dc4265e3ea971a335ba41a47c
refs/heads/master
2020-12-24T14:45:43.854896
2011-07-25T14:15:53
2011-07-25T14:15:53
2,096,630
1
3
null
null
null
null
UTF-8
C++
false
false
8,566
cpp
#include "text.hpp" using namespace std; static const wchar_t *g_whitespaces = L" \f\n\r\t\v"; // Simplified use of sprintf const char *fmt(const char *format, ...) { enum { MAX_MSG_SIZE = 512, MAX_USES = 8 }; static char buffer[MAX_USES][MAX_MSG_SIZE]; static int currentStr = 0; va_list va; currentStr = (currentStr + 1) % MAX_USES; va_start(va, format); vsnprintf(buffer[currentStr], MAX_MSG_SIZE, format, va); buffer[currentStr][MAX_MSG_SIZE - 1] = '\0'; va_end(va); return buffer[currentStr]; } // string sfmt(const char *format, ...) { va_list va; u32 length; char *tmp; string s; va_start(va, format); length = vsnprintf(0, 0, format, va) + 1; va_end(va); tmp = new char[length + 1]; va_start(va, format); vsnprintf(tmp, length, format, va); va_end(va); s = tmp; delete[] tmp; return s; } static inline bool fmtCount(const wstringEx &format, int &i, int &s) { int state = 0; i = 0; s = 0; for (u32 k = 0; k < format.size(); ++k) { if (state == 0) { if (format[k] == L'%') state = 1; } else if (state == 1) { switch (format[k]) { case L'%': state = 0; break; case L'i': case L'd': state = 0; ++i; break; case L's': state = 0; ++s; break; default: return false; } } } return true; } // Only handles the cases i need for translations : plain %i and %s bool checkFmt(const wstringEx &ref, const wstringEx &format) { int s; int i; int refs; int refi; if (!fmtCount(ref, refi, refs)) return false; if (!fmtCount(format, i, s)) return false; return i == refi && s == refs; } wstringEx wfmt(const wstringEx &format, ...) { // Don't care about performance va_list va; string f(format.toUTF8()); u32 length; char *tmp; va_start(va, format); length = vsnprintf(0, 0, f.c_str(), va) + 1; va_end(va); tmp = new char[length + 1]; va_start(va, format); vsnprintf(tmp, length, f.c_str(), va); va_end(va); wstringEx ws; ws.fromUTF8(tmp); delete[] tmp; return ws; } wstringEx vectorToString(const vector<wstringEx> &vect, char sep) { wstringEx s; for (u32 i = 0; i < vect.size(); ++i) { if (i > 0) s.push_back(sep); s.append(vect[i]); } return s; } vector<string> stringToVector(const string &text, char sep) { vector<string> v; if (text.empty()) return v; u32 count = 1; for (u32 i = 0; i < text.size(); ++i) if (text[i] == sep) ++count; v.reserve(count); string::size_type off = 0; string::size_type i = 0; do { i = text.find_first_of(sep, off); if (i != string::npos) { string ws(text.substr(off, i - off)); v.push_back(ws); off = i + 1; } else v.push_back(text.substr(off)); } while (i != string::npos); return v; } vector<wstringEx> stringToVector(const wstringEx &text, char sep) { vector<wstringEx> v; if (text.empty()) return v; u32 count = 1; for (u32 i = 0; i < text.size(); ++i) if (text[i] == sep) ++count; v.reserve(count); wstringEx::size_type off = 0; wstringEx::size_type i = 0; do { i = text.find_first_of(sep, off); if (i != wstringEx::npos) { wstringEx ws(text.substr(off, i - off)); v.push_back(ws); off = i + 1; } else v.push_back(text.substr(off)); } while (i != wstringEx::npos); return v; } bool SFont::fromBuffer(const u8 *buffer, u32 bufferSize, u32 size, u32 lspacing) { size = min(max(6u, size), 1000u); lspacing = min(max(6u, lspacing), 1000u); lineSpacing = lspacing; font.release(); data.release(); dataSize = 0; font = SmartPtr<FreeTypeGX>(new FreeTypeGX); if (!font) return false; font->loadFont(buffer, bufferSize, size, false); return true; } bool SFont::newSize(u32 size, u32 lspacing) { if (!data) return false; size = min(max(6u, size), 1000u); lspacing = min(max(6u, lspacing), 1000u); lineSpacing = lspacing; font.release(); font = SmartPtr<FreeTypeGX>(new FreeTypeGX); if (!font) return false; font->loadFont(data.get(), dataSize, size, false); return true; } bool SFont::fromFile(const char *filename, u32 size, u32 lspacing) { FILE *file; u32 fileSize; size = min(max(6u, size), 1000u); lspacing = min(max(6u, lspacing), 1000u); font.release(); data.release(); dataSize = 0; lineSpacing = lspacing; file = fopen(filename, "rb"); if (file == NULL) return false; fseek(file, 0, SEEK_END); fileSize = ftell(file); fseek(file, 0, SEEK_SET); if (fileSize == 0) return false; data = smartMem2Alloc(fileSize); // Use MEM2 because of big chinese fonts if (!!data) fread(data.get(), 1, fileSize, file); fclose(file); file = NULL; if (!data) return false; dataSize = fileSize; font = SmartPtr<FreeTypeGX>(new FreeTypeGX); if (!font) { data.release(); return false; } font->loadFont(data.get(), dataSize, size, false); return true; } void CText::setText(SFont font, const wstringEx &t) { CText::SWord w; vector<wstringEx> lines; m_lines.clear(); m_font = font; if (!m_font.font) return; // Don't care about performance lines = stringToVector(t, L'\n'); m_lines.reserve(lines.size()); // for (u32 k = 0; k < lines.size(); ++k) { wstringEx &l = lines[k]; m_lines.push_back(CText::CLine()); m_lines.back().reserve(32); wstringEx::size_type i = l.find_first_not_of(g_whitespaces); wstringEx::size_type j; while (i != wstringEx::npos) { j = l.find_first_of(g_whitespaces, i); if (j != wstringEx::npos && j > i) { w.text.assign(l, i, j - i); m_lines.back().push_back(w); i = l.find_first_not_of(g_whitespaces, j); } else if (j == wstringEx::npos) { w.text.assign(l, i, l.size() - i); m_lines.back().push_back(w); i = wstringEx::npos; } } } } void CText::setFrame(float width, u16 style, bool ignoreNewlines, bool instant) { float posX; float posY; float wordWidth; float space; float shift; u32 lineBeg; if (!m_font.font) return; space = m_font.font->getWidth(L" "); posX = 0.f; posY = 0.f; lineBeg = 0; for (u32 k = 0; k < m_lines.size(); ++k) { CText::CLine &words = m_lines[k]; if (words.empty()) posY += (float)m_font.lineSpacing; for (u32 i = 0; i < words.size(); ++i) { wordWidth = m_font.font->getWidth(words[i].text.c_str()); if (posX == 0.f || posX + (float)wordWidth <= width) { words[i].targetPos = Vector3D(posX, posY, 0.f); posX += wordWidth + space; } else { posY += (float)m_font.lineSpacing; words[i].targetPos = Vector3D(0.f, posY, 0.f); if ((style & (FTGX_JUSTIFY_CENTER | FTGX_JUSTIFY_RIGHT)) != 0) { posX -= space; shift = (style & FTGX_JUSTIFY_CENTER) != 0 ? -posX * 0.5f : -posX; for (u32 j = lineBeg; j < i; ++j) words[j].targetPos.x += shift; } posX = wordWidth + space; lineBeg = i; } } // Quick patch for newline support if (!ignoreNewlines && k + 1 < m_lines.size()) posX = 9999999.f; } if ((style & (FTGX_JUSTIFY_CENTER | FTGX_JUSTIFY_RIGHT)) != 0) { posX -= space; shift = (style & FTGX_JUSTIFY_CENTER) != 0 ? -posX * 0.5f : -posX; for (u32 k = 0; k < m_lines.size(); ++k) for (u32 j = lineBeg; j < m_lines[k].size(); ++j) m_lines[k][j].targetPos.x += shift; } if ((style & (FTGX_ALIGN_MIDDLE | FTGX_ALIGN_BOTTOM)) != 0) { posY += (float)m_font.lineSpacing; shift = (style & FTGX_ALIGN_MIDDLE) != 0 ? -posY * 0.5f : -posY; for (u32 k = 0; k < m_lines.size(); ++k) for (u32 j = 0; j < m_lines[k].size(); ++j) m_lines[k][j].targetPos.y += shift; } if (instant) for (u32 k = 0; k < m_lines.size(); ++k) for (u32 i = 0; i < m_lines[k].size(); ++i) m_lines[k][i].pos = m_lines[k][i].targetPos; } void CText::setColor(const CColor &c) { m_color = c; } void CText::tick(void) { for (u32 k = 0; k < m_lines.size(); ++k) for (u32 i = 0; i < m_lines[k].size(); ++i) m_lines[k][i].pos += (m_lines[k][i].targetPos - m_lines[k][i].pos) * 0.05f; } void CText::draw(void) { if (!m_font.font) return; for (u32 k = 0; k < m_lines.size(); ++k) for (u32 i = 0; i < m_lines[k].size(); ++i) { m_font.font->setX(m_lines[k][i].pos.x); m_font.font->setY(m_lines[k][i].pos.y); m_font.font->drawText(0, m_font.lineSpacing, m_lines[k][i].text.c_str(), m_color); } }
[ "[email protected]@a6d911d2-2a6f-2b2f-592f-0469abc2858f" ]
[ [ [ 1, 385 ] ] ]
f1db73dc3ee4db3341d2a59f8a994fdaedebcc10
1e01b697191a910a872e95ddfce27a91cebc57dd
/BNFReadCChar.cpp
74081ca6b2953594be96821448394369df2f5131
[]
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
6,792
cpp
/* "CodeWorker": a scripting language for parsing and generating text. Copyright (C) 1996-1997, 1999-2004 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 "UtlException.h" #ifndef WIN32 # include "UtlString.h" // for Debian/gcc 2.95.4 #endif #include "ScpStream.h" #include "CppCompilerEnvironment.h" #include "CGRuntime.h" #include "DtaScriptVariable.h" #include "ExprScriptVariable.h" #include "DtaBNFScript.h" #include "BNFClause.h" #include "DtaVisitor.h" #include "BNFReadCChar.h" namespace CodeWorker { BNFReadCChar::BNFReadCChar(DtaBNFScript* pBNFScript, GrfBlock* pParent, bool bContinue, bool bNoCase) : _pBNFScript(pBNFScript), GrfCommand(pParent), _pVariableToAssign(NULL), _bContinue(bContinue), _iClauseReturnType(BNFClause::NO_RETURN_TYPE), _bNoCase(bNoCase) {} BNFReadCChar::~BNFReadCChar() { delete _pVariableToAssign; } void BNFReadCChar::accept(DtaVisitor& visitor, DtaVisitorEnvironment& env) { visitor.visitBNFReadCChar(*this, env); } bool BNFReadCChar::isABNFCommand() const { return true; } void BNFReadCChar::setVariableToAssign(ExprScriptVariable* pVariableToAssign, bool bConcat, BNFClause& theClause) { if (pVariableToAssign != NULL) { _pVariableToAssign = pVariableToAssign; std::string sVariableName = _pVariableToAssign->toString(); if (sVariableName == theClause.getName()) _iClauseReturnType = theClause.getReturnType(); _bConcatVariable = bConcat; } } SEQUENCE_INTERRUPTION_LIST BNFReadCChar::executeInternal(DtaScriptVariable& visibility) { int iLocation = CGRuntime::getInputLocation(); int iImplicitCopyPosition = _pBNFScript->skipEmptyChars(visibility); int iNotEmptyLocation = CGRuntime::getInputLocation(); std::string sValue = CGRuntime::readCChar(); if (iNotEmptyLocation == CGRuntime::getInputLocation()) { BNF_SYMBOL_HAS_FAILED } if (!_listOfConstants.empty()) { bool bMatch = false; for (std::vector<std::string>::const_iterator i = _listOfConstants.begin(); i != _listOfConstants.end(); i++) { if (_bNoCase) bMatch = (stricmp(i->c_str(), sValue.c_str()) == 0); else bMatch = (*i == sValue); if (bMatch) break; } if (!bMatch) { BNF_SYMBOL_HAS_FAILED } } if (_pVariableToAssign != NULL) { DtaScriptVariable* pVariable = visibility.getVariable(*_pVariableToAssign); if (_iClauseReturnType == BNFClause::LIST_RETURN_TYPE) { pVariable->pushItem(sValue); } else { if (_bConcatVariable) pVariable->concatValue(sValue.c_str()); else pVariable->setValue(sValue.c_str()); } } if (iImplicitCopyPosition >= 0) { std::string sText = CGRuntime::getLastReadChars(CGRuntime::getInputLocation() - iNotEmptyLocation); _pBNFScript->writeBinaryData(sText.c_str(), sText.size()); } return NO_INTERRUPTION; } void BNFReadCChar::compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const { CW_BODY_INDENT << "// " << toString(); CW_BODY_ENDL; int iCursor = theCompilerEnvironment.newCursor(); CW_BODY_INDENT << "int _compilerClauseLocation_" << iCursor << " = CGRuntime::getInputLocation();";CW_BODY_ENDL; CW_BODY_INDENT << "int _compilerClauseImplicitCopy_" << iCursor << " = theEnvironment.skipEmptyChars();";CW_BODY_ENDL; CW_BODY_INDENT << "int _compilerClauseNotEmptyLocation_" << iCursor << " = CGRuntime::getInputLocation();";CW_BODY_ENDL; CW_BODY_INDENT << "std::string _compilerClauseText_" << iCursor << " = CGRuntime::readCChar();";CW_BODY_ENDL; CW_BODY_INDENT << "_compilerClauseSuccess = (_compilerClauseNotEmptyLocation_" << iCursor << " != _compilerClauseLocation_" << iCursor << ");";CW_BODY_ENDL; if (!_listOfConstants.empty()) { CW_BODY_INDENT << "if (_compilerClauseSuccess) {"; CW_BODY_ENDL; CW_BODY_INDENT << "\t_compilerClauseSuccess = "; for (std::vector<std::string>::const_iterator i = _listOfConstants.begin(); i != _listOfConstants.end(); i++) { if (i != _listOfConstants.begin()) CW_BODY_STREAM << " || "; CW_BODY_STREAM << "("; if (_bNoCase) { CW_BODY_STREAM << "stricmp(_compilerClauseText_" << iCursor << ".c_str(), "; CW_BODY_STREAM.writeString(*i); CW_BODY_STREAM << ") == 0"; } else { CW_BODY_STREAM << "_compilerClauseText_" << iCursor << " == "; CW_BODY_STREAM.writeString(*i); } CW_BODY_STREAM << ")"; } CW_BODY_STREAM << ";"; CW_BODY_ENDL; CW_BODY_INDENT << "}"; CW_BODY_ENDL; } if (_pVariableToAssign != NULL) { CW_BODY_INDENT << "if (_compilerClauseSuccess) {";CW_BODY_ENDL; theCompilerEnvironment.incrementIndentation(); char tcText[32]; sprintf(tcText, "_compilerClauseText_%d", iCursor); _pBNFScript->compileCppBNFAssignment(theCompilerEnvironment, _iClauseReturnType, *_pVariableToAssign, _bConcatVariable, tcText); theCompilerEnvironment.decrementIndentation(); CW_BODY_INDENT << "}";CW_BODY_ENDL; } CW_BODY_INDENT << "if (!_compilerClauseSuccess) {"; CW_BODY_ENDL; if (_bContinue) { CW_BODY_INDENT << "\tCGRuntime::throwBNFExecutionError("; CW_BODY_STREAM.writeString(toString()); CW_BODY_STREAM << ");"; } else { CW_BODY_INDENT << "\tCGRuntime::setInputLocation(_compilerClauseLocation_" << iCursor << ");"; CW_BODY_ENDL; CW_BODY_INDENT << "\tif (_compilerClauseImplicitCopy_" << iCursor << " >= 0) CGRuntime::resizeOutputStream(_compilerClauseImplicitCopy_" << iCursor << ");"; } CW_BODY_ENDL; CW_BODY_INDENT << "} else if (_compilerClauseImplicitCopy_" << iCursor << " >= 0) CGRuntime::writeBinaryData(_compilerClauseText_" << iCursor << ".c_str(), _compilerClauseText_" << iCursor << ".size());"; CW_BODY_ENDL; } std::string BNFReadCChar::toString() const { std::string sText = "#readCChar" + DtaBNFScript::constantsToString(_listOfConstants) + DtaBNFScript::assignmentToString(_pVariableToAssign, _bConcatVariable); if (_bContinue) sText = "#continue " + sText; return sText; } }
[ "cedric.p.r.lemaire@28b3f5f3-d42e-7560-b87f-5f53cf622bc4" ]
[ [ [ 1, 161 ] ] ]
8b28e8d30f7946755c4a54805ca770831ac6d0cf
0799179a3ee04268f474819d1d13f57cb8f78a4e
/bk/APIDSAA/ch5_binary_tree/Huffman/VarNode.h
68de5af786267bf14f2c1ad06c6624cbea1e3d2a
[]
no_license
brianm6/jcyangs-alg-trunk
5089185cf1554f7069cc43e86eebffdb8d6e4eec
b9cccc0de6e7eaf11f9f03e3a2c4abc3f24c2c89
refs/heads/master
2020-04-06T05:23:02.591366
2010-02-26T02:54:15
2010-02-26T02:54:15
32,643,574
0
0
null
null
null
null
UTF-8
C++
false
false
319
h
// Module Name: VarNode.h // Objective: provide the generic variable node implementation // Author: jcyang[at]ymail.com // Date: 3.Feb.2010 // Revision: alpha class VarBinNode { public: virtual bool isLeaf() = 0; }; template<class Elem> class LeafNode : public VarBinNode { public: LeafNode<Elem>*
[ "jcyangzh@18ebaf90-01a2-11df-b136-7f7962f7bc17" ]
[ [ [ 1, 15 ] ] ]
a705439a1baeb7925f5e33da60a58789297beb60
3daaefb69e57941b3dee2a616f62121a3939455a
/mgllib/src/input/MglKeyboardInput.h
e233e8480fa248e48306e4168e5b0ae788f57b0d
[]
no_license
myun2ext/open-mgl-legacy
21ccadab8b1569af8fc7e58cf494aaaceee32f1e
8faf07bad37a742f7174b454700066d53a384eae
refs/heads/master
2016-09-06T11:41:14.108963
2009-12-28T12:06:58
2009-12-28T12:06:58
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,807
h
////////////////////////////////////////////////////////// // // MglKeyboardInput v0.60.00 06/01/02 // - キーボード入力クラス // // v0.10.10 04/12/13 // ・m_stateBufゼロクリアしてねぇ(;´Д`)ゞ // // v0.10.25 05/03/02 // ・GetDeviceState()に失敗した時、 //  m_stateBufはゼロクリアしとかないとマズいっぽい。 // ・Init()の引数に dwCooperativeFlag 追加。 // // v0.10.26 05/03/04 // ・変数名等ちょこちょこ // // v0.20.00 06/01/02 // ・CMglKeyboardInputBaseに分離したり色々 // ////////////////////////////////////////////////////////// #ifndef __MglKeyboardInput_H__ #define __MglKeyboardInput_H__ #include "msl.h" #include "MglKeyboardInputBase.h" #define FAST_RT_ARY_SIZE (128) #define ASCII_BS (0x08) #define ASCII_BACKSPACE (0x08) /*#define ASCII_TAB (0x09) #define ASCII_HTAB (0x09)*/ #define ASCII_RETURN (0x0A) #define ASCII_ENTER (0x0A) #define ASCII_ESC (0x1B) #define ASCII_ESCAPE (0x1B) /*#define ASCII_SP (0x20) #define ASCII_SPACE (0x20)*/ #define ASCII_DELETE (0x7F) #define DIK_ERR (0x00) #define DIK_NULL (0x00) #define ASCII_NULL (0x00) // クラス宣言 class DLL_EXP CMglKeyboardInput : public CMglKeyboardInputBase { private: // m_kbFastRtAry 生成 static void GenRtAry(); // OnEvent系用 //BYTE m_prevStateBuf[STATEBUF_SIZE]; //CMglTimer m_timers[STATEBUF_SIZE]; <-- やっぱメモリとか食いすぎですよネー… //DWORD m_dwTimes[STATEBUF_SIZE]; protected: // キーボードのコード関連配列 static int m_kbFastRtAry[FAST_RT_ARY_SIZE]; // 本当は CMglKeyboardInput にあるべきな気が… static bool m_kbFastRtAryInited; // ↑本当はstaticであるべきなんだがとりあえず保留・・・ public: // コンストラクタ・デストラクタ CMglKeyboardInput(){ /*ZeroMemoryAS( m_kbFastRtAry ); ZeroMemoryAS( m_prevStateBuf );*/ } virtual ~CMglKeyboardInput(){} // 初期化 void Init( HWND hWnd, DWORD dwCooperativeFlag=DISCL_NONEXCLUSIVE|DISCL_FOREGROUND ){ CMglKeyboardInputBase::Init( hWnd, dwCooperativeFlag ); //GenRtAry(); } static BYTE GetDik( char c ){GenRtAry(); return m_kbFastRtAry[c]; } static BYTE GetAsciiToDik( char c ){GenRtAry(); return m_kbFastRtAry[c]; } static BYTE GetAscii2Dik( char c ){GenRtAry(); return m_kbFastRtAry[c]; } static BYTE AsciiToDik( char c ){GenRtAry(); return m_kbFastRtAry[c]; } static BYTE Ascii2Dik( char c ){GenRtAry(); return m_kbFastRtAry[c]; } static BYTE ASCII_TO_DIK( char c ){GenRtAry(); return m_kbFastRtAry[c]; } static BYTE ASCII2DIK( char c ){GenRtAry(); return m_kbFastRtAry[c]; } // オーバーライド /*void UpdateStateBuf(){ memcpy( m_prevStateBuf, m_stateBuf, sizeof(m_stateBuf) ); CMglKeyboardInputBase::UpdateStateBuf(); }*/ void Update(){ UpdateStateBuf(); } // 入力取得 int GetPressDikeyList( vector<BYTE> &keyListOut ); int GetPressKeyList( vector<char> &keyListOut ); char GetPressKey(){ // 最初の一つだけ vector<char> keylist; if ( GetPressKeyList(keylist) == 0 ) return EOF; else return keylist[0]; } // Update()必要 int GetOnDikey(); //int GetOnDikey( BYTE nDik ); int GetOnKey(); int GetOnKey( char cAsciiKeyCode ); // ***** int GetOnDikey(BYTE nDik){ return IsOnDownKey(nDik); } ///////////////////////////////////////////////////////////////////// // 押されたイベント BOOL IsOnDownKey(BYTE nDik){ if( GetStateChanged(nDik) > 0 ) return TRUE; else return FALSE; } // 離されたイベント BOOL IsOnUpKey(BYTE nDik){ if( GetStateChanged(nDik) < 0 ) return TRUE; else return FALSE; } }; #endif//__MglKeyboardInput_H__
[ "myun2@6d62ff88-fa28-0410-b5a4-834eb811a934" ]
[ [ [ 1, 133 ] ] ]
9e4e43be0e7c7455b9aa879c980a4d18899ba598
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/python/src/object/function.cpp
5d951b5b2b74477db0526877bd527bb724daa5af
[ "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
23,849
cpp
// Copyright David Abrahams 2001. // 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 <boost/python/docstring_options.hpp> #include <boost/python/object/function_object.hpp> #include <boost/python/object/function_handle.hpp> #include <boost/python/errors.hpp> #include <boost/python/str.hpp> #include <boost/python/object_attributes.hpp> #include <boost/python/args.hpp> #include <boost/python/refcount.hpp> #include <boost/python/extract.hpp> #include <boost/python/tuple.hpp> #include <boost/python/list.hpp> #include <boost/python/ssize_t.hpp> #include <boost/python/detail/signature.hpp> #include <boost/mpl/vector/vector10.hpp> #include <boost/bind.hpp> #include <algorithm> #include <cstring> #if BOOST_PYTHON_DEBUG_ERROR_MESSAGES # include <cstdio> #endif namespace boost { namespace python { volatile bool docstring_options::show_user_defined_ = true; volatile bool docstring_options::show_signatures_ = true; }} namespace boost { namespace python { namespace objects { py_function_impl_base::~py_function_impl_base() { } unsigned py_function_impl_base::max_arity() const { return this->min_arity(); } extern PyTypeObject function_type; function::function( py_function const& implementation #if BOOST_WORKAROUND(__EDG_VERSION__, == 245) , python::detail::keyword const* names_and_defaults #else , python::detail::keyword const* const names_and_defaults #endif , unsigned num_keywords ) : m_fn(implementation) , m_nkeyword_values(0) { if (names_and_defaults != 0) { unsigned int max_arity = m_fn.max_arity(); unsigned int keyword_offset = max_arity > num_keywords ? max_arity - num_keywords : 0; ssize_t tuple_size = num_keywords ? max_arity : 0; m_arg_names = object(handle<>(PyTuple_New(tuple_size))); if (num_keywords != 0) { for (unsigned j = 0; j < keyword_offset; ++j) PyTuple_SET_ITEM(m_arg_names.ptr(), j, incref(Py_None)); } for (unsigned i = 0; i < num_keywords; ++i) { tuple kv; python::detail::keyword const* const p = names_and_defaults + i; if (p->default_value) { kv = make_tuple(p->name, p->default_value); ++m_nkeyword_values; } else { kv = make_tuple(p->name); } PyTuple_SET_ITEM( m_arg_names.ptr() , i + keyword_offset , incref(kv.ptr()) ); } } PyObject* p = this; if (function_type.ob_type == 0) { function_type.ob_type = &PyType_Type; ::PyType_Ready(&function_type); } (void)( // warning suppression for GCC PyObject_INIT(p, &function_type) ); } function::~function() { } PyObject* function::call(PyObject* args, PyObject* keywords) const { std::size_t n_unnamed_actual = PyTuple_GET_SIZE(args); std::size_t n_keyword_actual = keywords ? PyDict_Size(keywords) : 0; std::size_t n_actual = n_unnamed_actual + n_keyword_actual; function const* f = this; // Try overloads looking for a match do { // Check for a plausible number of arguments unsigned min_arity = f->m_fn.min_arity(); unsigned max_arity = f->m_fn.max_arity(); if (n_actual + f->m_nkeyword_values >= min_arity && n_actual <= max_arity) { // This will be the args that actually get passed handle<>inner_args(allow_null(borrowed(args))); if (n_keyword_actual > 0 // Keyword arguments were supplied || n_actual < min_arity) // or default keyword values are needed { if (f->m_arg_names.ptr() == Py_None) { // this overload doesn't accept keywords inner_args = handle<>(); } else { // "all keywords are none" is a special case // indicating we will accept any number of keyword // arguments if (PyTuple_Size(f->m_arg_names.ptr()) == 0) { // no argument preprocessing } else if (n_actual > max_arity) { // too many arguments inner_args = handle<>(); } else { // build a new arg tuple, will adjust its size later assert(max_arity <= ssize_t_max); inner_args = handle<>( PyTuple_New(static_cast<ssize_t>(max_arity))); // Fill in the positional arguments for (std::size_t i = 0; i < n_unnamed_actual; ++i) PyTuple_SET_ITEM(inner_args.get(), i, incref(PyTuple_GET_ITEM(args, i))); // Grab remaining arguments by name from the keyword dictionary std::size_t n_actual_processed = n_unnamed_actual; for (std::size_t arg_pos = n_unnamed_actual; arg_pos < max_arity ; ++arg_pos) { // Get the keyword[, value pair] corresponding PyObject* kv = PyTuple_GET_ITEM(f->m_arg_names.ptr(), arg_pos); // If there were any keyword arguments, // look up the one we need for this // argument position PyObject* value = n_keyword_actual ? PyDict_GetItem(keywords, PyTuple_GET_ITEM(kv, 0)) : 0; if (!value) { // Not found; check if there's a default value if (PyTuple_GET_SIZE(kv) > 1) value = PyTuple_GET_ITEM(kv, 1); if (!value) { // still not found; matching fails PyErr_Clear(); inner_args = handle<>(); break; } } else { ++n_actual_processed; } PyTuple_SET_ITEM(inner_args.get(), arg_pos, incref(value)); } if (inner_args.get()) { //check if we proccessed all the arguments if(n_actual_processed < n_actual) inner_args = handle<>(); } } } } // Call the function. Pass keywords in case it's a // function accepting any number of keywords PyObject* result = inner_args ? f->m_fn(inner_args.get(), keywords) : 0; // If the result is NULL but no error was set, m_fn failed // the argument-matching test. // This assumes that all other error-reporters are // well-behaved and never return NULL to python without // setting an error. if (result != 0 || PyErr_Occurred()) return result; } f = f->m_overloads.get(); } while (f); // None of the overloads matched; time to generate the error message argument_error(args, keywords); return 0; } object function::signature(bool show_return_type) const { py_function const& impl = m_fn; python::detail::signature_element const* return_type = impl.signature(); python::detail::signature_element const* s = return_type + 1; list formal_params; if (impl.max_arity() == 0) formal_params.append("void"); for (unsigned n = 0; n < impl.max_arity(); ++n) { if (s[n].basename == 0) { formal_params.append("..."); break; } str param(s[n].basename); if (s[n].lvalue) param += " {lvalue}"; if (m_arg_names) // None or empty tuple will test false { object kv(m_arg_names[n]); if (kv) { char const* const fmt = len(kv) > 1 ? " %s=%r" : " %s"; param += fmt % kv; } } formal_params.append(param); } if (show_return_type) return "%s(%s) -> %s" % make_tuple( m_name, str(", ").join(formal_params), return_type->basename); return "%s(%s)" % make_tuple( m_name, str(", ").join(formal_params)); } object function::signatures(bool show_return_type) const { list result; for (function const* f = this; f; f = f->m_overloads.get()) { result.append(f->signature(show_return_type)); } return result; } void function::argument_error(PyObject* args, PyObject* /*keywords*/) const { static handle<> exception( PyErr_NewException("Boost.Python.ArgumentError", PyExc_TypeError, 0)); object message = "Python argument types in\n %s.%s(" % make_tuple(this->m_namespace, this->m_name); list actual_args; for (ssize_t i = 0; i < PyTuple_Size(args); ++i) { char const* name = PyTuple_GetItem(args, i)->ob_type->tp_name; actual_args.append(str(name)); } message += str(", ").join(actual_args); message += ")\ndid not match C++ signature:\n "; message += str("\n ").join(signatures()); #if BOOST_PYTHON_DEBUG_ERROR_MESSAGES std::printf("\n--------\n%s\n--------\n", extract<const char*>(message)()); #endif PyErr_SetObject(exception.get(), message.ptr()); throw_error_already_set(); } void function::add_overload(handle<function> const& overload_) { function* parent = this; while (parent->m_overloads) parent = parent->m_overloads.get(); parent->m_overloads = overload_; // If we have no documentation, get the docs from the overload if (!m_doc) m_doc = overload_->m_doc; } namespace { char const* const binary_operator_names[] = { "add__", "and__", "div__", "divmod__", "eq__", "floordiv__", "ge__", "gt__", "le__", "lshift__", "lt__", "mod__", "mul__", "ne__", "or__", "pow__", "radd__", "rand__", "rdiv__", "rdivmod__", "rfloordiv__", "rlshift__", "rmod__", "rmul__", "ror__", "rpow__", "rrshift__", "rshift__", "rsub__", "rtruediv__", "rxor__", "sub__", "truediv__", "xor__" }; struct less_cstring { bool operator()(char const* x, char const* y) const { return BOOST_CSTD_::strcmp(x,y) < 0; } }; inline bool is_binary_operator(char const* name) { return name[0] == '_' && name[1] == '_' && std::binary_search( &binary_operator_names[0] , binary_operator_names + sizeof(binary_operator_names)/sizeof(*binary_operator_names) , name + 2 , less_cstring() ); } // Something for the end of the chain of binary operators PyObject* not_implemented(PyObject*, PyObject*) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } handle<function> not_implemented_function() { static object keeper( function_object( py_function(&not_implemented, mpl::vector1<void>(), 2) , python::detail::keyword_range()) ); return handle<function>(borrowed(downcast<function>(keeper.ptr()))); } } void function::add_to_namespace( object const& name_space, char const* name_, object const& attribute) { add_to_namespace(name_space, name_, attribute, 0); } void function::add_to_namespace( object const& name_space, char const* name_, object const& attribute, char const* doc) { str const name(name_); PyObject* const ns = name_space.ptr(); if (attribute.ptr()->ob_type == &function_type) { function* new_func = downcast<function>(attribute.ptr()); PyObject* dict = 0; if (PyClass_Check(ns)) dict = ((PyClassObject*)ns)->cl_dict; else if (PyType_Check(ns)) dict = ((PyTypeObject*)ns)->tp_dict; else dict = PyObject_GetAttrString(ns, "__dict__"); if (dict == 0) throw_error_already_set(); handle<> existing(allow_null(::PyObject_GetItem(dict, name.ptr()))); if (existing) { if (existing->ob_type == &function_type) { new_func->add_overload( handle<function>( borrowed( downcast<function>(existing.get()) ) ) ); } else if (existing->ob_type == &PyStaticMethod_Type) { char const* name_space_name = extract<char const*>(name_space.attr("__name__")); ::PyErr_Format( PyExc_RuntimeError , "Boost.Python - All overloads must be exported " "before calling \'class_<...>(\"%s\").staticmethod(\"%s\")\'" , name_space_name , name_ ); throw_error_already_set(); } } else if (is_binary_operator(name_)) { // Binary operators need an additional overload which // returns NotImplemented, so that Python will try the // __rxxx__ functions on the other operand. We add this // when no overloads for the operator already exist. new_func->add_overload(not_implemented_function()); } // A function is named the first time it is added to a namespace. if (new_func->name().ptr() == Py_None) new_func->m_name = name; handle<> name_space_name( allow_null(::PyObject_GetAttrString(name_space.ptr(), "__name__"))); if (name_space_name) new_func->m_namespace = object(name_space_name); } // The PyObject_GetAttrString() or PyObject_GetItem calls above may // have left an active error PyErr_Clear(); if (PyObject_SetAttr(ns, name.ptr(), attribute.ptr()) < 0) throw_error_already_set(); object mutable_attribute(attribute); if (doc != 0 && docstring_options::show_user_defined_) { // Accumulate documentation if ( PyObject_HasAttrString(mutable_attribute.ptr(), "__doc__") && mutable_attribute.attr("__doc__")) { mutable_attribute.attr("__doc__") += "\n\n"; mutable_attribute.attr("__doc__") += doc; } else { mutable_attribute.attr("__doc__") = doc; } } if (docstring_options::show_signatures_) { if ( PyObject_HasAttrString(mutable_attribute.ptr(), "__doc__") && mutable_attribute.attr("__doc__")) { mutable_attribute.attr("__doc__") += "\n"; } else { mutable_attribute.attr("__doc__") = ""; } function* f = downcast<function>(attribute.ptr()); mutable_attribute.attr("__doc__") += str("\n ").join(make_tuple( "C++ signature:", f->signature(true))); } } BOOST_PYTHON_DECL void add_to_namespace( object const& name_space, char const* name, object const& attribute) { function::add_to_namespace(name_space, name, attribute, 0); } BOOST_PYTHON_DECL void add_to_namespace( object const& name_space, char const* name, object const& attribute, char const* doc) { function::add_to_namespace(name_space, name, attribute, doc); } namespace { struct bind_return { bind_return(PyObject*& result, function const* f, PyObject* args, PyObject* keywords) : m_result(result) , m_f(f) , m_args(args) , m_keywords(keywords) {} void operator()() const { m_result = m_f->call(m_args, m_keywords); } private: PyObject*& m_result; function const* m_f; PyObject* m_args; PyObject* m_keywords; }; } extern "C" { // Stolen from Python's funcobject.c static PyObject * function_descr_get(PyObject *func, PyObject *obj, PyObject *type_) { if (obj == Py_None) obj = NULL; return PyMethod_New(func, obj, type_); } static void function_dealloc(PyObject* p) { delete static_cast<function*>(p); } static PyObject * function_call(PyObject *func, PyObject *args, PyObject *kw) { PyObject* result = 0; handle_exception(bind_return(result, static_cast<function*>(func), args, kw)); return result; } // // Here we're using the function's tp_getset rather than its // tp_members to set up __doc__ and __name__, because tp_members // really depends on having a POD object type (it relies on // offsets). It might make sense to reformulate function as a POD // at some point, but this is much more expedient. // static PyObject* function_get_doc(PyObject* op, void*) { function* f = downcast<function>(op); return python::incref(f->doc().ptr()); } static int function_set_doc(PyObject* op, PyObject* doc, void*) { function* f = downcast<function>(op); f->doc(doc ? object(python::detail::borrowed_reference(doc)) : object()); return 0; } static PyObject* function_get_name(PyObject* op, void*) { function* f = downcast<function>(op); if (f->name().ptr() == Py_None) return PyString_InternFromString("<unnamed Boost.Python function>"); else return python::incref(f->name().ptr()); } // We add a dummy __class__ attribute in order to fool PyDoc into // treating these as built-in functions and scanning their // documentation static PyObject* function_get_class(PyObject* /*op*/, void*) { return python::incref(upcast<PyObject>(&PyCFunction_Type)); } } static PyGetSetDef function_getsetlist[] = { {"__name__", (getter)function_get_name, 0, 0, 0 }, {"func_name", (getter)function_get_name, 0, 0, 0 }, {"__class__", (getter)function_get_class, 0, 0, 0 }, // see note above {"__doc__", (getter)function_get_doc, (setter)function_set_doc, 0, 0}, {"func_doc", (getter)function_get_doc, (setter)function_set_doc, 0, 0}, {NULL, 0, 0, 0, 0} /* Sentinel */ }; PyTypeObject function_type = { PyObject_HEAD_INIT(0) 0, "Boost.Python.function", sizeof(function), 0, (destructor)function_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, //(reprfunc)func_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ function_call, /* tp_call */ 0, /* tp_str */ 0, // PyObject_GenericGetAttr, /* tp_getattro */ 0, // PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT /* | Py_TPFLAGS_HAVE_GC */,/* tp_flags */ 0, /* tp_doc */ 0, // (traverseproc)func_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, //offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, // func_memberlist, /* tp_members */ function_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ function_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ 0, //offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ #if PYTHON_API_VERSION >= 1012 0 /* tp_del */ #endif }; object function_object( py_function const& f , python::detail::keyword_range const& keywords) { return python::object( python::detail::new_non_null_reference( new function( f, keywords.first, keywords.second - keywords.first))); } object function_object(py_function const& f) { return function_object(f, python::detail::keyword_range()); } handle<> function_handle_impl(py_function const& f) { return python::handle<>( allow_null( new function(f, 0, 0))); } } // namespace objects namespace detail { object BOOST_PYTHON_DECL make_raw_function(objects::py_function f) { static keyword k; return objects::function_object( f , keyword_range(&k,&k)); } void BOOST_PYTHON_DECL pure_virtual_called() { PyErr_SetString(PyExc_RuntimeError, "Pure virtual function called"); throw_error_already_set(); } } }} // namespace boost::python
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 724 ] ] ]
791273b4338e686ec344c03a8fd22c70cf6e37dc
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/InformationProviders/CachedImageInfoProvider/CachedImageInfoProvider.cpp
6498f5ab9e5f61afa7b25f29437c932eff9e968f
[]
no_license
outcast1000/Jaangle
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
18feb537068f1f3be6ecaa8a4b663b917c429e3d
refs/heads/master
2020-04-08T20:04:56.875651
2010-12-25T10:44:38
2010-12-25T10:44:38
19,334,292
3
0
null
null
null
null
UTF-8
C++
false
false
12,267
cpp
// /* // * // * Copyright (C) 2003-2010 Alexandros Economou // * // * This file is part of Jaangle (http://www.jaangle.com) // * // * This Program is free software; you can redistribute it and/or modify // * it under the terms of the GNU General Public License as published by // * the Free Software Foundation; either version 2, or (at your option) // * any later version. // * // * This Program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU General Public License for more details. // * // * You should have received a copy of the GNU General Public License // * along with GNU Make; see the file COPYING. If not, write to // * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. // * http://www.gnu.org/copyleft/gpl.html // * // */ #include "stdafx.h" #include "CachedImageInfoProvider.h" #include "cStringUtils.h" #include "shlwapi.h" #include "cMD5.h" #ifdef _UNITTESTING LPCTSTR tempDir = _T("D:\\temp"); void DeleteTempDir() { SHFILEOPSTRUCT fop; fop.hwnd = 0; fop.wFunc = FO_DELETE; fop.pFrom = tempDir; fop.pTo = NULL; fop.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT; fop.fAnyOperationsAborted = FALSE; fop.hNameMappings = NULL; fop.lpszProgressTitle = _T("Deleting..."); SHFileOperation(&fop); }; const int lastSizeOf = 140; BOOL CachedImageInfoProvider::UnitTest() { if (lastSizeOf != sizeof(CachedImageInfoProvider)) TRACE(_T("TestCachedImageInfoProvider. Object Size Changed. Was: %d - Is: %d\r\n"), lastSizeOf, sizeof(CachedImageInfoProvider)); DeleteTempDir(); CachedImageInfoProvider ip; ip.SetStoragePath(tempDir); Request req(IInfoProvider::SRV_ArtistImage); req.artist = _T("Nick Cave"); if (ip.OpenRequest(req)) { Result res; UNITTEST(ip.GetNextResult(res) == FALSE); res.main = _T("D:\\My Photos\\2007\\03 Canada-Cuba\\IMG_0594.jpg"); res.additionalInfo = _T(""); res.service = IInfoProvider::SRV_ArtistImage; ip.AddResult(res); res.main = _T("D:\\My Photos\\2007\\03 Canada-Cuba\\IMG_0595.jpg"); ip.AddResult(res); } if (ip.OpenRequest(req)) { DWORD resNum = 0; Result res; while (ip.GetNextResult(res)) { UNITTEST(res.IsValid()); TRACE(_T("Result %d. %s\r\n"), resNum++, res.main); } } req.service = IInfoProvider::SRV_AlbumImage; req.artist = _T("Nick Cave"); req.album = _T("Kapoio ALbum"); if (ip.OpenRequest(req)) { Result res; res.additionalInfo = _T(""); res.service = IInfoProvider::SRV_ArtistImage; UNITTEST(ip.GetNextResult(res) == FALSE); res.main = _T("D:\\My Photos\\2007\\03 Canada-Cuba\\IMG_0594.jpg"); ip.AddResult(res); res.main = _T("D:\\My Photos\\2007\\03 Canada-Cuba\\IMG_0595.jpg"); ip.AddResult(res); } if (ip.OpenRequest(req)) { DWORD resNum = 0; Result res; while (ip.GetNextResult(res)) { UNITTEST(res.IsValid()); TRACE(_T("Result %d. %s\r\n"), resNum++, res.main); } } DeleteTempDir(); return TRUE; } #endif CachedImageInfoProvider::CachedImageInfoProvider(): m_request(SRV_First), m_curResult(-1) { } CachedImageInfoProvider::~CachedImageInfoProvider() { } IInfoProvider* CachedImageInfoProvider::Clone() const { CachedImageInfoProvider* pIP = new CachedImageInfoProvider; pIP->SetInternetHandle(GetInternetHandle()); IConfigurableHelper::TransferConfiguration(*this, *pIP); pIP->SetStoragePath(m_storagePath.c_str()); return pIP; } BOOL CachedImageInfoProvider::CanHandle(ServiceEnum service) const { switch (service) { case IInfoProvider::SRV_ArtistImage: case IInfoProvider::SRV_AlbumImage: return TRUE; } return FALSE; } BOOL CachedImageInfoProvider::OpenRequest(const Request& request) { m_curResult = -1; ASSERT(request.IsValid()); if (!request.IsValid()) return FALSE; m_results.clear(); switch (request.service) { case IInfoProvider::SRV_ArtistImage: m_Artist = request.artist; m_request.artist = m_Artist.c_str(); m_request.album = NULL; break; case IInfoProvider::SRV_AlbumImage: m_Artist = request.artist; m_Album = request.album; m_request.artist = m_Artist.c_str(); m_request.album = m_Album.c_str(); break; default: return FALSE; } m_request.service = request.service; return TRUE; } BOOL CachedImageInfoProvider::GetFiles(LPCTSTR path, std::vector<std::basic_string<TCHAR> >& files) { WIN32_FIND_DATA dta; HANDLE hFileFinder = FindFirstFile(path, &dta); if (hFileFinder != INVALID_HANDLE_VALUE) { do { TCHAR bf[MAX_PATH]; bf[MAX_PATH - 1] = 0; _sntprintf(bf, MAX_PATH, _T("%s%s"), m_storagePath.c_str(), dta.cFileName); if (bf[MAX_PATH - 1] == 0) files.push_back(bf); } while(FindNextFile(hFileFinder, &dta)); FindClose(hFileFinder); } return files.size() > 0; } void CachedImageInfoProvider::GetArtistHash(LPTSTR hash, UINT hashLen) { cMD5 md5; TCHAR hashString[500]; INT posStart = 0; if (_tcsnicmp(m_Artist.c_str(), _T("the "), 4) == 0) posStart = 4; _sntprintf(hashString, 500,_T("%s"), &m_Artist.c_str()[posStart]); _tcslwr(hashString); _tcsncpy(hash, CA2CT(md5.CalcMD5FromWString(hashString)), hashLen); } void CachedImageInfoProvider::GetAlbumHash(LPTSTR hash, UINT hashLen) { cMD5 md5; TCHAR hashString[500]; INT posStart = 0; if (_tcsnicmp(m_Artist.c_str(), _T("the "), 4) == 0) posStart = 4; _sntprintf(hashString, 500,_T("%s-%s"), &m_Artist.c_str()[posStart], m_Album.c_str()); _tcslwr(hashString); _tcsncpy(hash, CA2CT(md5.CalcMD5FromWString(hashString)), hashLen); } void CachedImageInfoProvider::ConvertV2ArtistPictures() { cMD5 md5; TCHAR path[MAX_PATH]; //--- Format v2 _sntprintf(path, MAX_PATH,_T("%s%s??.???"), m_storagePath.c_str(), CA2CT(md5.CalcMD5FromString(CT2CA(m_Artist.c_str())))); WIN32_FIND_DATA dta; HANDLE hFileFinder = FindFirstFile(path, &dta); if (hFileFinder != INVALID_HANDLE_VALUE) { do { TCHAR bf[MAX_PATH]; bf[MAX_PATH - 1] = 0; _sntprintf(bf, MAX_PATH, _T("%s%s"), m_storagePath.c_str(), dta.cFileName); if (bf[MAX_PATH - 1] == 0) { Result res; res.service = SRV_ArtistImage; res.main = bf; AddResult(res); DeleteFile(bf); } } while(FindNextFile(hFileFinder, &dta)); FindClose(hFileFinder); } //--- Format v1 //TCHAR artist[MAX_PATH]; //_tcsncpy(artist, m_Artist.c_str(), MAX_PATH); //_tcschrrep(INVALID_CHARS_FOR_FILENAME, '_', artist); //_sntprintf(path, MAX_PATH,_T("%s%.20s??.???"), m_storagePath.c_str(), artist); //GetFiles(path, m_results); } void CachedImageInfoProvider::ConvertV2AlbumPictures() { cMD5 md5; TCHAR path[MAX_PATH]; //--- Format v2 _sntprintf(path, MAX_PATH,_T("%s-%s"), m_Artist.c_str(), m_Album.c_str()); _sntprintf(path, MAX_PATH,_T("%s%s??.???"), m_storagePath.c_str(), CA2CT(md5.CalcMD5FromString(CT2CA(path)))); WIN32_FIND_DATA dta; HANDLE hFileFinder = FindFirstFile(path, &dta); if (hFileFinder != INVALID_HANDLE_VALUE) { do { TCHAR bf[MAX_PATH]; bf[MAX_PATH - 1] = 0; _sntprintf(bf, MAX_PATH, _T("%s%s"), m_storagePath.c_str(), dta.cFileName); if (bf[MAX_PATH - 1] == 0) { Result res; res.service = SRV_AlbumImage; res.main = bf; AddResult(res); DeleteFile(bf); } } while(FindNextFile(hFileFinder, &dta)); FindClose(hFileFinder); } //--- Format v1 //TCHAR artist[MAX_PATH]; //_tcsncpy(artist, m_Artist.c_str(), MAX_PATH); //_tcschrrep(INVALID_CHARS_FOR_FILENAME, '_', artist); //_sntprintf(path, MAX_PATH,_T("%s%.20s??.???"), m_storagePath.c_str(), artist); //GetFiles(path, m_results); } BOOL CachedImageInfoProvider::GetNextResult(Result& result) { if (m_curResult == -1) { m_results.clear(); TCHAR path[MAX_PATH]; TCHAR hash[500]; switch (m_request.service) { case SRV_ArtistImage: ConvertV2ArtistPictures(); GetArtistHash(hash, 500); _sntprintf(path, MAX_PATH, _T("%sAR_%s??.*"), m_storagePath.c_str(), hash); GetFiles(path, m_results); break; case SRV_AlbumImage: ConvertV2AlbumPictures(); GetAlbumHash(hash, 500); _sntprintf(path, MAX_PATH,_T("%sAL_%s??.*"), m_storagePath.c_str(), hash); GetFiles(path, m_results); break; } } m_curResult++; if (m_curResult < 0 || m_curResult >= (INT)m_results.size()) return FALSE; result.main = m_results[m_curResult].c_str(); result.additionalInfo = m_storagePath.c_str(); return TRUE; } void CachedImageInfoProvider::SetStoragePath(LPCTSTR storagePath) { ASSERT(storagePath != NULL); m_storagePath = storagePath; if (m_storagePath[m_storagePath.size() - 1] != '\\') m_storagePath += '\\'; if (!PathFileExists(m_storagePath.c_str())) CreateDirectory(m_storagePath.c_str(), NULL); } BOOL CachedImageInfoProvider::AddResult(const Result& result) { ASSERT(result.IsValid()); TCHAR path[MAX_PATH]; TCHAR hash[500]; switch (result.service) { case SRV_ArtistImage: { GetArtistHash(hash, 500); _sntprintf(path, MAX_PATH,_T("%sAR_%s"), m_storagePath.c_str(), hash); return SaveFile(path, _T("jpg"), result.main); } break; case SRV_AlbumImage: { GetAlbumHash(hash, 500); _sntprintf(path, MAX_PATH,_T("%sAL_%s"), m_storagePath.c_str(), hash); return SaveFile(path, _T("jpg"), result.main); } break; } return FALSE; } INT CachedImageInfoProvider::GetFileSize(LPCTSTR fileName) { ASSERT(fileName != NULL); HANDLE f= CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (f != INVALID_HANDLE_VALUE) { DWORD fs = ::GetFileSize(f, NULL); CloseHandle(f); return INT(fs); } return -1; } BOOL CachedImageInfoProvider::SaveFile(LPCTSTR mainPath, LPCTSTR extension, LPCTSTR srcPath) { TCHAR trgPathTemplate[MAX_PATH]; _sntprintf(trgPathTemplate, MAX_PATH, _T("%s??.%s"), mainPath, extension); INT srcFileSize = GetFileSize(srcPath); WIN32_FIND_DATA dta; HANDLE hFileFinder = FindFirstFile(trgPathTemplate, &dta); if (hFileFinder != INVALID_HANDLE_VALUE) { BOOL bFoundSameSize = FALSE; do { if (dta.nFileSizeLow == srcFileSize) { bFoundSameSize = TRUE; break; } }while (FindNextFile(hFileFinder, &dta)); FindClose(hFileFinder); if (bFoundSameSize) return FALSE; } TCHAR newPath[MAX_PATH]; for (int i=0; i<0xff; i++) { _sntprintf(newPath, MAX_PATH, _T("%s%0.2X.%s"), mainPath, i, extension); if (!PathFileExists(newPath))//Does not exist return CopyFile(srcPath, newPath, TRUE) != 0; } return FALSE; } //BOOL CachedImageInfoProvider::DeleteFiles(LPCTSTR path) //{ // ASSERT(path != NULL); // WIN32_FIND_DATA dta; // HANDLE hFileFinder = FindFirstFile(path, &dta); // if (hFileFinder == INVALID_HANDLE_VALUE) // return TRUE;//Files Not Found // BOOL bRet = TRUE; // TCHAR bf[MAX_PATH]; // while (TRUE) // { // bf[MAX_PATH - 1] = 0; // _sntprintf(bf, MAX_PATH, _T("%s%s"), m_storagePath.c_str(), dta.cFileName); // if (bf[MAX_PATH - 1] != 0) // { // ASSERT(!_T("File Name TOO Long")); // bRet = FALSE; // break; // } // if (!DeleteFile(bf)) // { // bRet = FALSE; // break; // } // if (!FindNextFile(hFileFinder, &dta)) // break; // } // FindClose(hFileFinder); // return bRet; //} BOOL CachedImageInfoProvider::DeleteResult() { if (m_curResult >= 0 && m_curResult < (INT)m_results.size()) return DeleteFile(m_results[m_curResult].c_str()); return FALSE; } LPCTSTR CachedImageInfoProvider::GetModuleInfo(ModuleInfo mi) const { switch (mi) { case IPI_UniqueID: return _T("CACH"); case IPI_Name: return _T("Cached Images"); case IPI_Author: return _T("Alex Economou"); case IPI_VersionStr: return _T("1"); case IPI_VersionNum: return _T("1"); case IPI_Description: return _T("Cached Images"); case IPI_HomePage: return _T("http://teenspirit.artificialspirit.com"); case IPI_Email: return _T("[email protected]"); } return NULL; }
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 452 ] ] ]
da9a2d466c7bbe50b79a7a1ca9e10a7bed9a0b67
6eef3e34d3fe47a10336a53df1a96a591b15cd01
/ASearch/AlkalineServer/AdderThread.hpp
fc47f834886e56130d96cbb586b3d7683419c29e
[]
no_license
praveenmunagapati/alkaline
25013c233a80b07869e0fdbcf9b8dfa7888cc32e
7cf43b115d3e40ba48854f80aca8d83b67f345ce
refs/heads/master
2021-05-27T16:44:12.356701
2009-10-29T11:23:09
2009-10-29T11:23:09
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
954
hpp
/* © Vestris Inc., Geneva, Switzerland http://www.vestris.com, 1994-1999 All Rights Reserved _____________________________________________________ written by Daniel Doubrovkine - [email protected] URL Adder Thread, part of the Alkaline Search Engine adds addresses posted online asynchronously from the reindexing thread, allows to return control to the client immediately and schedule a longer term operation */ #ifndef ALKALINE_ADDER_THREAD #define ALKALINE_ADDER_THREAD #include <platform/include.hpp> #include <String/String.hpp> #include <Site/Site.hpp> #include <Thread/Thread.hpp> typedef enum { AtAdd, AtRemove } CAdderOperation; class CAdderThread : public CThread { property(CAdderOperation, AdderOperation); copy_property(CSite *, Site); property(CString, Url); public: CAdderThread(void); virtual ~CAdderThread(void); virtual void Execute(void * Arguments); }; #endif
[ [ [ 1, 37 ] ] ]
a607dc511985aa3d8a8be0ad805944dfe2436516
55196303f36aa20da255031a8f115b6af83e7d11
/private/bikini/base/string.cpp
191cd7fd9e29bb5bb237dbe8469c0e8b89bab1e7
[]
no_license
Heartbroken/bikini
3f5447647d39587ffe15a7ae5badab3300d2a2ff
fe74f51a3a5d281c671d303632ff38be84d23dd7
refs/heads/master
2021-01-10T19:48:40.851837
2010-05-25T19:58:52
2010-05-25T19:58:52
37,190,932
0
0
null
null
null
null
UTF-8
C++
false
false
3,213
cpp
/*---------------------------------------------------------------------------------------------*//* Binary Kinematics 3 - C++ Game Programming Library Copyright (C) 2008-2010 Viktor Reutskyy [email protected] *//*---------------------------------------------------------------------------------------------*/ #include "header.hpp" namespace bk { /*--------------------------------------------------------------------------------*/ astring utf8(const wstring &_s) { uint l_wlength = _s.length(); uint l_alength = WideCharToMultiByte(CP_UTF8, 0, _s.c_str(), (int)l_wlength, 0, 0, 0, 0); astring l_s; l_s.resize(l_alength); WideCharToMultiByte(CP_UTF8, 0, _s.c_str(), (int)l_wlength, &l_s[0], (int)l_alength, 0, 0); return l_s; } wstring utf8(const astring &_s) { uint l_alength = _s.length(); uint l_wlength = MultiByteToWideChar(CP_UTF8, 0, _s.c_str(), (int)l_alength, 0, 0); wstring l_s; l_s.resize(l_wlength); MultiByteToWideChar(CP_UTF8, 0, _s.c_str(), (int)l_alength, &l_s[0], (int)l_wlength); return l_s; } //_string format(const _string &_format, ...) //{ // va_list l_args; // va_start(l_args, _format); // // const uint l_buffer_max = 1024; // achar l_buffer[l_buffer_max]; // // sint l_length = vsprintf_s(l_buffer, _format, l_args); // // if (l_length <= 0) return ""; // // l_buffer[l_length] = 0; // // static achar_array l_data; // l_data.assign(l_buffer, l_buffer + l_length + 1); // // va_end(l_args); // // return &l_data[0]; //} _string _format(const wchar* _f, ...) { va_list l_args; va_start(l_args, _f); const uint l_buffer_max = 1024; wchar l_buffer[l_buffer_max]; sint l_length = vswprintf_s(l_buffer, _f, l_args); if (l_length <= 0) return L""; l_buffer[l_length] = 0; static wchar_array l_data; l_data.assign(l_buffer, l_buffer + l_length + 1); va_end(l_args); return &l_data[0]; } _string print_GUID(const GUID &_g) { return format("{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", _g.Data1, _g.Data2, _g.Data3, _g.Data4[0], _g.Data4[1], _g.Data4[2], _g.Data4[3], _g.Data4[4], _g.Data4[5], _g.Data4[6], _g.Data4[7]); } //GUID scan_GUID(const astring &_s) //{ // byte l_buff[18]; GUID &l_g = *(GUID*)l_buff; // if (sscanf_s(_s.c_str(), "{%lx-%hx-%hx-%hx-%llx}", &l_g.Data1, &l_g.Data2, &l_g.Data3, &l_g.Data4[0], &l_g.Data4[2]) != 5) return bad_GUID; // swap(l_g.Data4[0], l_g.Data4[1]); // swap(l_g.Data4[2], l_g.Data4[7]); // swap(l_g.Data4[3], l_g.Data4[6]); // swap(l_g.Data4[4], l_g.Data4[5]); // return l_g; //} GUID scan_GUID(const _string &_s) { byte l_buff[18]; GUID &l_g = *(GUID*)l_buff; if (swscanf_s(_s.wstr.c_str(), L"{%lx-%hx-%hx-%hx-%llx}", &l_g.Data1, &l_g.Data2, &l_g.Data3, &l_g.Data4[0], &l_g.Data4[2]) != 5 && swscanf_s(_s.wstr.c_str(), L"%lx-%hx-%hx-%hx-%llx", &l_g.Data1, &l_g.Data2, &l_g.Data3, &l_g.Data4[0], &l_g.Data4[2]) != 5) return bad_GUID; swap(l_g.Data4[0], l_g.Data4[1]); swap(l_g.Data4[2], l_g.Data4[7]); swap(l_g.Data4[3], l_g.Data4[6]); swap(l_g.Data4[4], l_g.Data4[5]); return l_g; } } /* namespace bk -------------------------------------------------------------------------------*/
[ "viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587" ]
[ [ [ 1, 102 ] ] ]
6fa1b98be600f2d0d4b77f958cafe919b66de1fc
d4f885fe63812c80103c222d55ba30eda376183c
/devctrl.cpp
a2f26e49f014aafcbd6e2aa3ca819a6452055c44
[]
no_license
wjcsharp/devctrl
4036d08ad193f88647f19d05f6ac63e77598bfec
855fdabdb74857cdd4602d273e5ddb98bd9b623d
refs/heads/master
2021-01-10T02:17:23.977915
2010-07-27T09:40:34
2010-07-27T09:40:34
47,730,136
0
1
null
null
null
null
WINDOWS-1251
C++
false
false
43,537
cpp
#include "devctrl.h" #pragma prefast(push) #pragma prefast(disable: 6011) #pragma prefast(disable: 6387) #include "devctrl.tmh" #pragma prefast(pop) #include "devlist.h" #include "inc/devctrlex.h" GLOBAL_DATA Globals; PWCHAR DevStrings[] = { DEV_TYPE_USB_CLASS_RESERVED, DEV_TYPE_USB_CLASS_AUDIO, DEV_TYPE_USB_CLASS_COMMUNICATIONS, DEV_TYPE_USB_CLASS_HUMAN_INTERFACE, DEV_TYPE_USB_CLASS_MONITOR, DEV_TYPE_USB_CLASS_PHYSICAL_INTERFACE, DEV_TYPE_USB_CLASS_POWER, DEV_TYPE_USB_CLASS_PRINTER, DEV_TYPE_USB_CLASS_STORAGE, DEV_TYPE_USB_CLASS_HUB, DEV_TYPE_USB_CLASS_VENDOR_SPECIFIC, }; typedef struct _DEVOBJ_EXTENSION_HEADER { CSHORT Type; //: Int2B USHORT Size; //: Uint2B PDEVICE_OBJECT DeviceObject; //: Ptr32 _DEVICE_OBJECT ULONG PowerFlags; //: Uint4B PVOID Dope; //: Ptr32 _DEVICE_OBJECT_POWER_EXTENSION ULONG ExtensionFlags; //: Uint4B PVOID DeviceNode; //: Ptr32 Void PDEVICE_OBJECT AttachedTo; //: Ptr32 _DEVICE_OBJECT }DEVOBJ_EXTENSION_HEADER, *PDEVOBJ_EXTENSION_HEADER; typedef struct _DEVICE_NODE_WXP_HEADER { PVOID Sibling; //: Ptr32 _DEVICE_NODE PVOID Child; //: Ptr32 _DEVICE_NODE PVOID Parent; //: Ptr32 _DEVICE_NODE PVOID LastChild; //: Ptr32 _DEVICE_NODE ULONG Level; //: Uint4B PVOID Notify; //: Ptr32 _PO_DEVICE_NOTIFY ULONG State; //: _PNP_DEVNODE_STATE ULONG PreviousState; //: _PNP_DEVNODE_STATE ULONG StateHistory[20]; //: [20] _PNP_DEVNODE_STATE ULONG StateHistoryEntry; //: Uint4B NTSTATUS CompletionStatus; //: Int4B PIRP PendingIrp; //: Ptr32 _IRP ULONG Flags; //: Uint4B ULONG UserFlags; //: Uint4B ULONG Problem; //: Uint4B PDEVICE_OBJECT PhysicalDeviceObject; //: Ptr32 _DEVICE_OBJECT PCM_RESOURCE_LIST ResourceList; //: Ptr32 _CM_RESOURCE_LIST PCM_RESOURCE_LIST ResourceListTranslated; //: Ptr32 _CM_RESOURCE_LIST UNICODE_STRING InstancePath; //: _UNICODE_STRING UNICODE_STRING ServiceName; //: _UNICODE_STRING }DEVICE_NODE_WXP_HEADER,*PDEVICE_NODE_WXP_HEADER; typedef struct _PO_DEVICE_NOTIFY_VISTA { LIST_ENTRY Link; //: _LIST_ENTRY PDEVICE_OBJECT TargetDevice; //: Ptr32 _DEVICE_OBJECT UCHAR OrderLevel; //: UChar PDEVICE_OBJECT DeviceObject; //: Ptr32 _DEVICE_OBJECT PWCHAR DeviceName; //: Ptr32 Uint2B PWCHAR DriverName; //: Ptr32 Uint2B ULONG ChildCount; //: Uint4B ULONG ActiveChild; //: Uint4B }PO_DEVICE_NOTIFY_VISTA,*PPO_DEVICE_NOTIFY_VISTA; typedef struct _PO_IRP_QUEUE_VISTA { PIRP CurrentIrp; //: Ptr32 _IRP PIRP PendingIrpList; //: Ptr32 _IRP }PO_IRP_QUEUE_VISTA, *PPO_IRP_QUEUE_VISTA; typedef struct _PO_IRP_MANAGER_VISTA { PO_IRP_QUEUE_VISTA DeviceIrpQueue; //: _PO_IRP_QUEUE PO_IRP_QUEUE_VISTA SystemIrpQueue; //: _PO_IRP_QUEUE }PO_IRP_MANAGER_VISTA,*PPO_IRP_MANAGER_VISTA; typedef struct _DEVICE_NODE_VISTA_HEADER { PVOID Sibling; //: Ptr32 _DEVICE_NODE PVOID Child; //: Ptr32 _DEVICE_NODE PVOID Parent; //: Ptr32 _DEVICE_NODE PVOID LastChild; //: Ptr32 _DEVICE_NODE ULONG Level; //: Uint4B PO_DEVICE_NOTIFY_VISTA Notify; //: _PO_DEVICE_NOTIFY PO_IRP_MANAGER_VISTA PoIrpManager; //: _PO_IRP_MANAGER ULONG State; //: _PNP_DEVNODE_STATE ULONG PreviousState; //: _PNP_DEVNODE_STATE ULONG StateHistory[20]; //: [20] _PNP_DEVNODE_STATE ULONG StateHistoryEntry; //: Uint4B NTSTATUS CompletionStatus; //: Int4B PIRP PendingIrp; //: Ptr32 _IRP ULONG Flags; //: Uint4B ULONG UserFlags; //: Uint4B ULONG Problem; //: Uint4B PDEVICE_OBJECT PhysicalDeviceObject; //: Ptr32 _DEVICE_OBJECT PCM_RESOURCE_LIST ResourceList; //: Ptr32 _CM_RESOURCE_LIST PCM_RESOURCE_LIST ResourceListTranslated; //: Ptr32 _CM_RESOURCE_LIST UNICODE_STRING InstancePath; //: _UNICODE_STRING UNICODE_STRING ServiceName; //: _UNICODE_STRING }DEVICE_NODE_VISTA_HEADER,*PDEVICE_NODE_VISTA_HEADER; typedef struct _DEVICE_NODE_W7_HEADER { PVOID Sibling; //: Ptr64 to struct _DEVICE_NODE, 54 elements, 0x268 bytes PVOID Child; //: Ptr64 to struct _DEVICE_NODE, 54 elements, 0x268 bytes PVOID Parent; //: Ptr64 to struct _DEVICE_NODE, 54 elements, 0x268 bytes PVOID LastChild; //: Ptr64 to struct _DEVICE_NODE, 54 elements, 0x268 bytes PDEVICE_OBJECT PhysicalDeviceObject; //: Ptr64 to struct _DEVICE_OBJECT, 25 elements, 0x150 bytes UNICODE_STRING InstancePath; //: struct _UNICODE_STRING, 3 elements, 0x10 bytes UNICODE_STRING ServiceName; //: struct _UNICODE_STRING, 3 elements, 0x10 bytes }DEVICE_NODE_W7_HEADER, *PDEVICE_NODE_W7_HEADER; BOOLEAN __drv_acquiresCriticalRegion AcquireResourceExclusive ( __inout __drv_acquiresResource( ExResourceType ) PERESOURCE pResource ) { BOOLEAN ret; ASSERT( ARGUMENT_PRESENT( pResource ) ); #pragma prefast(suppress: 28103) KeEnterCriticalRegion(); ret = ExAcquireResourceExclusiveLite( pResource, TRUE ); return ret; } VOID __drv_releasesCriticalRegion __drv_mustHoldCriticalRegion ReleaseResource ( __inout __drv_releasesResource( ExResourceType) PERESOURCE pResource ) { ASSERT( ARGUMENT_PRESENT( pResource ) ); ExReleaseResourceLite( pResource ); KeLeaveCriticalRegion(); } extern "C" NTSTATUS DriverEntry ( __in PDRIVER_OBJECT DriverObject, __in PUNICODE_STRING RegistryPath ) { NTSTATUS status = STATUS_SUCCESS; PDRIVER_DISPATCH *dispatch; UNICODE_STRING parameters; WPP_INIT_TRACING( DriverObject, RegistryPath ); RtlZeroMemory( &Globals, sizeof( Globals ) ); ExInitializeResourceLite( &Globals.m_DeviceListLock ); InitializeListHead( &Globals.m_DeviceList ); for ( ULONG ulIndex = 0; ulIndex <= IRP_MJ_MAXIMUM_FUNCTION; ulIndex++ ) { #pragma prefast(suppress: 28169, "__drv_dispatchType ignored") DriverObject->MajorFunction[ulIndex] = FilterPass; } DriverObject->MajorFunction[IRP_MJ_PNP] = FilterDispatchPnp; DriverObject->MajorFunction[IRP_MJ_POWER] = FilterDispatchPower; DriverObject->DriverExtension->AddDevice = FilterAddDevice; DriverObject->DriverUnload = FilterUnload; // filtering points DriverObject->MajorFunction[IRP_MJ_CREATE] = DriverObject->MajorFunction[IRP_MJ_CLOSE] = DriverObject->MajorFunction[IRP_MJ_CLEANUP] = DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DriverObject->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] = FilterDispatchIo; ExInitializeFastMutex( &Globals.m_ControlMutex ); FilterCreateControlObject( RegistryPath, DriverObject ); return status; } __checkReturn NTSTATUS GetClassGuidName ( __in PDEVICE_OBJECT PhysicalDeviceObject, __deref_out_opt PWCHAR *pwcGuidName ) { NTSTATUS status = STATUS_UNSUCCESSFUL; ULONG retSize = 0; ASSERT( ARGUMENT_PRESENT( PhysicalDeviceObject ) ); ASSERT( ARGUMENT_PRESENT( pwcGuidName ) ); status = IoGetDeviceProperty ( PhysicalDeviceObject, DevicePropertyClassGuid, 0, *pwcGuidName, &retSize ); if ( STATUS_BUFFER_TOO_SMALL != status ) { return status; } *pwcGuidName = (PWCHAR) ExAllocatePoolWithTag ( PagedPool, retSize, _ALLOC_TAG ); if ( !*pwcGuidName ) { return STATUS_INSUFFICIENT_RESOURCES; } status = IoGetDeviceProperty ( PhysicalDeviceObject, DevicePropertyClassGuid, retSize, *pwcGuidName, &retSize ); if ( !NT_SUCCESS( status ) ) { FREE_POOL( pwcGuidName ); } return status; } //! \todo - switch to UNICODE_STRING int TypeCompare ( __in PWCHAR wcGuidType, __in PWCHAR wcDevType ) { ASSERT( ARGUMENT_PRESENT( wcGuidType ) ); ASSERT( ARGUMENT_PRESENT( wcDevType ) ); ULONG wcGuidTypeLen; ULONG wcDevTypeLen; wcGuidTypeLen = (ULONG)wcslen( wcGuidType ); wcDevTypeLen = (ULONG)wcslen( wcDevType ); if ( wcDevTypeLen > wcGuidTypeLen ) { return 1; } return _wcsnicmp( wcGuidType, wcDevType, wcDevTypeLen ); } PWCHAR GetDevType ( __in PWCHAR wcGuidType ) { ASSERT( ARGUMENT_PRESENT( wcGuidType ) ); for ( int cou = 0; cou < RTL_NUMBER_OF( DevStrings ); cou++ ) { if ( !TypeCompare( wcGuidType, DevStrings[cou] ) ) { return DevStrings[ cou ]; } } return DEV_TYPE_OTHER; } __checkReturn NTSTATUS IopSynchronousCall( __in PDEVICE_OBJECT DeviceObject, __in PIO_STACK_LOCATION TopStackLocation, __deref_out_opt PVOID *Information ) { PIRP irp; PIO_STACK_LOCATION irpSp; IO_STATUS_BLOCK statusBlock; KEVENT event; NTSTATUS status; PULONG_PTR returnInfo = (PULONG_PTR) Information; ASSERT( ARGUMENT_PRESENT( DeviceObject ) ); ASSERT( ARGUMENT_PRESENT( TopStackLocation ) ); KeInitializeEvent ( &event, SynchronizationEvent, FALSE ); irp = IoBuildSynchronousFsdRequest ( IRP_MJ_PNP, DeviceObject, NULL, 0, NULL, &event, &statusBlock ); if ( !irp ) { __debugbreak(); return STATUS_INSUFFICIENT_RESOURCES; } irpSp = IoGetNextIrpStackLocation( irp ); // Copy in the caller-supplied stack location contents *irpSp = *TopStackLocation; status = IoCallDriver( DeviceObject, irp ); if ( STATUS_PENDING == status ) { KeWaitForSingleObject ( &event, Executive, KernelMode, FALSE, (PLARGE_INTEGER) NULL ); status = statusBlock.Status; } if ( NT_SUCCESS( status ) ) { *returnInfo = (ULONG_PTR) statusBlock.Information; } return status; } __checkReturn NTSTATUS IopQueryBus ( __in PDEVICE_OBJECT DeviceObject, __in BUS_QUERY_ID_TYPE IdType, __deref_out_opt PVOID *UniqueId ) { IO_STACK_LOCATION irpSp; NTSTATUS status; ASSERT( ARGUMENT_PRESENT( DeviceObject ) ); RtlZeroMemory( &irpSp, sizeof( IO_STACK_LOCATION ) ); irpSp.MajorFunction = IRP_MJ_PNP; irpSp.MinorFunction = IRP_MN_QUERY_ID; irpSp.Parameters.QueryId.IdType = IdType; status = IopSynchronousCall( DeviceObject, &irpSp, UniqueId ); return status; } __checkReturn NTSTATUS IopQueryDeviceText ( __in PDEVICE_OBJECT DeviceObject, __deref_out_opt PVOID *Description ) { LCID PsDefaultSystemLocaleId = 0x00000409; IO_STACK_LOCATION irpSp; NTSTATUS status; RtlZeroMemory( &irpSp, sizeof( IO_STACK_LOCATION ) ); irpSp.MajorFunction = IRP_MJ_PNP; irpSp.MinorFunction = IRP_MN_QUERY_DEVICE_TEXT; irpSp.Parameters.QueryDeviceText.DeviceTextType = DeviceTextDescription; irpSp.Parameters.QueryDeviceText.LocaleId = PsDefaultSystemLocaleId; status = IopSynchronousCall( DeviceObject, &irpSp, Description ); return status; } __checkReturn NTSTATUS GetClassGuidType ( __in PDEVICE_OBJECT PhysicalDeviceObject, __deref_out_opt PWCHAR *pwcGuidType ) { //! query device info function NTSTATUS status = STATUS_UNSUCCESSFUL; ULONG retSize = 0; PWCHAR buf = NULL; PWCHAR wcdevType = NULL; PWCHAR id = NULL; /*PWCHAR InstanceID = NULL, DeviceID = NULL, SerialNumber = NULL, HardwareIDs = NULL, CompatibleIDs = NULL, Description = NULL; status = IopQueryBus ( PhysicalDeviceObject, BusQueryInstanceID, (PVOID*) &InstanceID ); CHECK_RETURN( status, InstanceID ); status = IopQueryBus ( PhysicalDeviceObject, BusQueryDeviceID, (PVOID*) &DeviceID ); CHECK_RETURN( status, DeviceID ); status = IopQueryBus ( PhysicalDeviceObject, BusQueryDeviceSerialNumber, (PVOID*) &SerialNumber ); CHECK_RETURN( status, SerialNumber ); status = IopQueryBus ( PhysicalDeviceObject, BusQueryHardwareIDs, (PVOID*) &HardwareIDs ); CHECK_RETURN( status, HardwareIDs ); status = IopQueryBus ( PhysicalDeviceObject, BusQueryCompatibleIDs, (PVOID*) &CompatibleIDs ); CHECK_RETURN( status, CompatibleIDs ); status = IopQueryDeviceText ( PhysicalDeviceObject, (PVOID*) &Description ); CHECK_RETURN( status, Description ); FREE_POOL( InstanceID ); FREE_POOL( DeviceID ); FREE_POOL( SerialNumber ); FREE_POOL( HardwareIDs ); FREE_POOL( CompatibleIDs ); FREE_POOL( Description );*/ status = IoGetDeviceProperty ( PhysicalDeviceObject, DevicePropertyCompatibleIDs, 0, buf, &retSize ); if ( STATUS_BUFFER_TOO_SMALL != status ) { return status; } buf = (PWCHAR) ExAllocatePoolWithTag( PagedPool, retSize, _ALLOC_TAG ); if ( !buf ) { return STATUS_NO_MEMORY; } status = IoGetDeviceProperty ( PhysicalDeviceObject, DevicePropertyCompatibleIDs, retSize, buf, &retSize ); if ( !NT_SUCCESS( status ) ) { FREE_POOL( buf ); return status; } wcdevType = GetDevType( buf ); FREE_POOL( buf ); retSize = (ULONG)( ( wcslen( wcdevType ) + 1 ) * sizeof( WCHAR ) ); *pwcGuidType = (PWCHAR) ExAllocatePoolWithTag ( PagedPool, retSize, _ALLOC_TAG ); if ( !(*pwcGuidType) ) { return STATUS_NO_MEMORY; } //! \todo remove zeromemory RtlZeroMemory( *pwcGuidType, retSize ); RtlCopyMemory( *pwcGuidType, wcdevType, retSize ); return STATUS_SUCCESS; } __checkReturn NTSTATUS QueryCapabilities ( __in PDEVICE_OBJECT pDevice, __out PULONG IsEnuque ) { PIRP Irp; PIO_STACK_LOCATION irpSp; IO_STATUS_BLOCK statusBlock; KEVENT event; NTSTATUS status; DEVICE_CAPABILITIES capabilities; RtlZeroMemory( &capabilities, sizeof( capabilities ) ); KeInitializeEvent ( &event, SynchronizationEvent, FALSE ); __try { Irp = IoBuildSynchronousFsdRequest ( IRP_MJ_PNP, pDevice, NULL, 0, NULL, &event, &statusBlock ); if ( !Irp ) { status = STATUS_INSUFFICIENT_RESOURCES; __leave; } KeInitializeEvent ( &event, SynchronizationEvent, FALSE ); irpSp = IoGetNextIrpStackLocation( Irp ); irpSp->MinorFunction = IRP_MN_QUERY_CAPABILITIES; irpSp->Parameters.DeviceCapabilities.Capabilities = &capabilities; status = IoCallDriver( pDevice, Irp ); if ( STATUS_PENDING == status ) { KeWaitForSingleObject ( &event, Executive, KernelMode, FALSE, (PLARGE_INTEGER) NULL ); status = statusBlock.Status; } if ( NT_SUCCESS( status ) ) { *IsEnuque = capabilities.UniqueID; } } __finally { } return status; } NTSTATUS GetSerialId ( __in PDEVICE_OBJECT PhysicalDeviceObject, __out PUNICODE_STRING SerialID ) { NTSTATUS status = STATUS_UNSUCCESSFUL; ULONG MjOsVersion = 0; ULONG MiOsVersion = 0; ULONG BuildNumber = 0; PUNICODE_STRING InstancePath = NULL; ASSERT( PhysicalDeviceObject ); ASSERT( SerialID ); __try { PsGetVersion ( &MjOsVersion, &MiOsVersion, &BuildNumber, NULL ); switch( MjOsVersion ) { case 5: switch ( MiOsVersion ) { case 0: __debugbreak(); break; case 1: case 2: { PDEVOBJ_EXTENSION_HEADER pDevExt = (PDEVOBJ_EXTENSION_HEADER)PhysicalDeviceObject->DeviceObjectExtension; PDEVICE_NODE_WXP_HEADER pDevNode = (PDEVICE_NODE_WXP_HEADER)pDevExt->DeviceNode; InstancePath = &pDevNode->InstancePath; } break; default: __debugbreak(); break; } break; case 6: switch ( MiOsVersion ) { case 0: { PDEVOBJ_EXTENSION_HEADER pDevExt = (PDEVOBJ_EXTENSION_HEADER)PhysicalDeviceObject->DeviceObjectExtension; PDEVICE_NODE_VISTA_HEADER pDevNode = (PDEVICE_NODE_VISTA_HEADER)pDevExt->DeviceNode; InstancePath = &pDevNode->InstancePath; } break; case 1: { PDEVOBJ_EXTENSION_HEADER pDevExt = (PDEVOBJ_EXTENSION_HEADER)PhysicalDeviceObject->DeviceObjectExtension; PDEVICE_NODE_W7_HEADER pDevNode = (PDEVICE_NODE_W7_HEADER)pDevExt->DeviceNode; InstancePath = &pDevNode->InstancePath; } break; default: __debugbreak(); break; } break; default: __debugbreak(); break; } if ( !InstancePath ) { __leave; } if ( InstancePath->Length > 0x300 ) { __debugbreak(); __leave; } SerialID->Buffer = (PWCH) ExAllocatePoolWithTag ( PagedPool, InstancePath->Length, _ALLOC_TAG ); if ( !SerialID->Buffer ) { status = STATUS_NO_MEMORY; __leave; } RtlZeroMemory( SerialID->Buffer, InstancePath->Length ); SerialID->Length = InstancePath->Length; SerialID->MaximumLength = InstancePath->Length; RtlCopyMemory ( SerialID->Buffer, InstancePath->Buffer, InstancePath->Length ); status = STATUS_SUCCESS; } __finally { } return status; } #pragma prefast(push) #pragma prefast(disable: 28152, "DO_DEVICE_INITIALIZING flag") NTSTATUS FilterAddDevice ( __in PDRIVER_OBJECT DriverObject, __in PDEVICE_OBJECT PhysicalDeviceObject ) #pragma prefast(pop) /*++ Routine Description: The Plug & Play subsystem is handing us a brand new PDO, for which we (by means of INF registration) have been asked to provide a driver. We need to determine if we need to be in the driver stack for the device. Create a function device object to attach to the stack Initialize that device object Return status success. Remember: We can NOT actually send ANY non pnp IRPS to the given driver stack, UNTIL we have received an IRP_MN_START_DEVICE. Arguments: DeviceObject - pointer to a device object. PhysicalDeviceObject - pointer to a device object created by the underlying bus driver. Return Value: NT status code. --*/ { NTSTATUS status = STATUS_SUCCESS; PDEVICE_OBJECT deviceObject = NULL; PDEVICE_EXTENSION deviceExtension; ULONG deviceType = FILE_DEVICE_UNKNOWN; // // Create a filter device object. // if ( *InitSafeBootMode > 0 ) { return STATUS_SUCCESS; } status = IoCreateDevice ( DriverObject, sizeof( DEVICE_EXTENSION ), NULL, // No Name deviceType, FILE_DEVICE_SECURE_OPEN, FALSE, &deviceObject ); if ( !NT_SUCCESS( status ) ) { // // Returning failure here prevents the entire stack from functioning, // but most likely the rest of the stack will not be able to create // device objects either, so it is still OK. // return status; } deviceExtension = (PDEVICE_EXTENSION) deviceObject->DeviceExtension; deviceExtension->m_CommonData.Type = DEVICE_TYPE_FIDO; RtlInitEmptyUnicodeString ( &deviceExtension->DeviceId, NULL, 0 ); PWCHAR wcStr = NULL; BOOLEAN needLog = FALSE; RtlZeroMemory( &deviceExtension->DevName, sizeof( DEVICE_NAME ) ); status = GetClassGuidName( PhysicalDeviceObject, &wcStr ); if ( !NT_SUCCESS( status ) ) { IoDeleteDevice( deviceObject ); return STATUS_SUCCESS; } RtlInitUnicodeString( &deviceExtension->DevName.usGuid, wcStr ); status = GetClassGuidType( PhysicalDeviceObject, &wcStr ); if ( !NT_SUCCESS( status ) ) { if ( deviceExtension->DevName.usGuid.Buffer ) { FREE_POOL( deviceExtension->DevName.usGuid.Buffer ); } IoDeleteDevice( deviceObject ); return STATUS_SUCCESS; } RtlInitUnicodeString( &deviceExtension->DevName.usDeviceType, wcStr ); status = GetSerialId ( PhysicalDeviceObject, &deviceExtension->DeviceId ); if ( !NT_SUCCESS ( status ) ) { RtlInitEmptyUnicodeString ( &deviceExtension->DeviceId, NULL, 0 ); } ULONG isenuque; status = QueryCapabilities( PhysicalDeviceObject, &isenuque ); if ( !NT_SUCCESS ( status ) ) { ASSERT( !NT_SUCCESS( status ) ); isenuque = 0; } deviceExtension->IsUnique = isenuque; status = InsertDeviceList( &deviceExtension->DevName ); if ( !NT_SUCCESS( status ) ) { FREE_POOL( deviceExtension->DevName.usGuid.Buffer ); FREE_POOL( deviceExtension->DevName.usDeviceType.Buffer ); FREE_POOL( deviceExtension->DeviceId.Buffer ); IoDeleteDevice(deviceObject); //если не можем добавить элемент, то не фильтруем устройство, а система должна продолжать работать return STATUS_SUCCESS; } deviceExtension->NextLowerDriver = IoAttachDeviceToDeviceStack ( deviceObject, PhysicalDeviceObject); // // Failure for attachment is an indication of a broken plug & play system. // if ( !deviceExtension->NextLowerDriver ) { IoDeleteDevice( deviceObject ); return STATUS_UNSUCCESSFUL; } deviceObject->Flags |= deviceExtension->NextLowerDriver->Flags & (DO_BUFFERED_IO | DO_DIRECT_IO | DO_POWER_PAGABLE ); deviceObject->DeviceType = deviceExtension->NextLowerDriver->DeviceType; deviceObject->Characteristics = deviceExtension->NextLowerDriver->Characteristics; deviceExtension->Self = deviceObject; // // Let us use remove lock to keep count of IRPs so that we don't // deteach and delete our deviceobject until all pending I/Os in our // devstack are completed. Remlock is required to protect us from // various race conditions where our driver can get unloaded while we // are still running dispatch or completion code. // IoInitializeRemoveLock ( &deviceExtension->RemoveLock, _ALLOC_TAG, 1, // MaxLockedMinutes 100 ); INITIALIZE_PNP_STATE( deviceExtension ); deviceObject->Flags &= ~DO_DEVICE_INITIALIZING; return STATUS_SUCCESS; } __checkReturn NTSTATUS FilterPass ( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ) { PDEVICE_EXTENSION deviceExtension; NTSTATUS status; deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension; status = IoAcquireRemoveLock( &deviceExtension->RemoveLock, Irp ); if ( !NT_SUCCESS( status ) ) { Irp->IoStatus.Status = status; IoCompleteRequest( Irp, IO_NO_INCREMENT ); return status; } IoSkipCurrentIrpStackLocation ( Irp ); status = IoCallDriver( deviceExtension->NextLowerDriver, Irp ); IoReleaseRemoveLock( &deviceExtension->RemoveLock, Irp ); return status; } __checkReturn NTSTATUS FilterDispatchPnp ( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ) { PDEVICE_EXTENSION deviceExtension; PIO_STACK_LOCATION irpStack; NTSTATUS status; KEVENT event; deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension; irpStack = IoGetCurrentIrpStackLocation( Irp ); status = IoAcquireRemoveLock( &deviceExtension->RemoveLock, Irp ); if ( !NT_SUCCESS( status ) ) { Irp->IoStatus.Status = status; IoCompleteRequest( Irp, IO_NO_INCREMENT ); return status; } switch ( irpStack->MinorFunction ) { case IRP_MN_START_DEVICE: // // The device is starting. // We cannot touch the device (send it any non pnp irps) until a // start device has been passed down to the lower drivers. // KeInitializeEvent( &event, NotificationEvent, FALSE); IoCopyCurrentIrpStackLocationToNext( Irp ); IoSetCompletionRoutine(Irp, FilterStartCompletionRoutine, &event, TRUE, TRUE, TRUE); status = IoCallDriver(deviceExtension->NextLowerDriver, Irp); // // Wait for lower drivers to be done with the Irp. Important thing to // note here is when you allocate memory for an event in the stack // you must do a KernelMode wait instead of UserMode to prevent // the stack from getting paged out. // if ( STATUS_PENDING == status ) { KeWaitForSingleObject( &event, Executive, KernelMode, FALSE, NULL ); status = Irp->IoStatus.Status; } /*if ( !IsAllowAccess( deviceExtension->DevName.usGuid, deviceExtension->DevName.usDeviceType, NULL ) ) { status = STATUS_ACCESS_DENIED; }*/ if ( NT_SUCCESS( status ) ) { SET_NEW_PNP_STATE( deviceExtension, Started ); // On the way up inherit FILE_REMOVABLE_MEDIA during Start. // This characteristic is available only after the driver // stack is started!. if ( FlagOn ( deviceExtension->NextLowerDriver->Characteristics, FILE_REMOVABLE_MEDIA ) ) { SetFlag( DeviceObject->Characteristics, FILE_REMOVABLE_MEDIA ); } } Irp->IoStatus.Status = status; IoCompleteRequest( Irp, IO_NO_INCREMENT ); IoReleaseRemoveLock( &deviceExtension->RemoveLock, Irp ); return status; case IRP_MN_REMOVE_DEVICE: // Wait for all outstanding requests to complete IoReleaseRemoveLockAndWait( &deviceExtension->RemoveLock, Irp ); IoSkipCurrentIrpStackLocation( Irp ); status = IoCallDriver( deviceExtension->NextLowerDriver, Irp ); SET_NEW_PNP_STATE( deviceExtension, Deleted ); RemItemFromDeviceList( &deviceExtension->DevName ); FREE_POOL( deviceExtension->DevName.usDeviceType.Buffer ); FREE_POOL( deviceExtension->DevName.usGuid.Buffer ); FREE_POOL( deviceExtension->DeviceId.Buffer ); IoDetachDevice( deviceExtension->NextLowerDriver ); IoDeleteDevice( DeviceObject ); return status; case IRP_MN_QUERY_STOP_DEVICE: SET_NEW_PNP_STATE( deviceExtension, StopPending ); status = STATUS_SUCCESS; break; case IRP_MN_CANCEL_STOP_DEVICE: // Check to see whether you have received cancel-stop // without first receiving a query-stop. This could happen if someone // above us fails a query-stop and passes down the subsequent // cancel-stop. if ( StopPending == deviceExtension->DevicePnPState ) { // We did receive a query-stop, so restore. RESTORE_PREVIOUS_PNP_STATE( deviceExtension ); } status = STATUS_SUCCESS; // We must not fail this IRP. break; case IRP_MN_STOP_DEVICE: SET_NEW_PNP_STATE( deviceExtension, Stopped ); status = STATUS_SUCCESS; break; case IRP_MN_QUERY_REMOVE_DEVICE: SET_NEW_PNP_STATE( deviceExtension, RemovePending ); status = STATUS_SUCCESS; break; case IRP_MN_SURPRISE_REMOVAL: SET_NEW_PNP_STATE( deviceExtension, SurpriseRemovePending ); status = STATUS_SUCCESS; break; case IRP_MN_CANCEL_REMOVE_DEVICE: // Check to see whether you have received cancel-remove // without first receiving a query-remove. This could happen if // someone above us fails a query-remove and passes down the // subsequent cancel-remove. if ( RemovePending == deviceExtension->DevicePnPState ) { // We did receive a query-remove, so restore. RESTORE_PREVIOUS_PNP_STATE( deviceExtension ); } status = STATUS_SUCCESS; // We must not fail this IRP. break; case IRP_MN_DEVICE_USAGE_NOTIFICATION: // On the way down, pagable might become set. Mimic the driver // above us. If no one is above us, just set pagable. if ( !DeviceObject->AttachedDevice || FlagOn( DeviceObject->AttachedDevice->Flags, DO_POWER_PAGABLE ) ) { SetFlag( DeviceObject->Flags, DO_POWER_PAGABLE ); } IoCopyCurrentIrpStackLocationToNext( Irp ); IoSetCompletionRoutine( Irp, FilterDeviceUsageNotificationCompletionRoutine, NULL, TRUE, TRUE, TRUE ); return IoCallDriver( deviceExtension->NextLowerDriver, Irp ); default: // If you don't handle any IRP you must leave the // status as is. status = Irp->IoStatus.Status; break; } // Pass the IRP down and forget it. Irp->IoStatus.Status = status; IoSkipCurrentIrpStackLocation( Irp ); status = IoCallDriver( deviceExtension->NextLowerDriver, Irp ); IoReleaseRemoveLock( &deviceExtension->RemoveLock, Irp ); return status; } __checkReturn NTSTATUS FilterStartCompletionRoutine ( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp, __in PVOID Context ) { PKEVENT event = (PKEVENT) Context; UNREFERENCED_PARAMETER( DeviceObject ); // If the lower driver didn't return STATUS_PENDING, we don't need to // set the event because we won't be waiting on it. // This optimization avoids grabbing the dispatcher lock, and improves perf. if ( Irp->PendingReturned ) { ASSERT( event ); if ( event ) { KeSetEvent( event, IO_NO_INCREMENT, FALSE ); } } // The dispatch routine will have to call IoCompleteRequest return STATUS_MORE_PROCESSING_REQUIRED; } __checkReturn NTSTATUS FilterDeviceUsageNotificationCompletionRoutine ( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp, __in PVOID Context ) { PDEVICE_EXTENSION deviceExtension; UNREFERENCED_PARAMETER( Context ); deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension; if ( Irp->PendingReturned ) { IoMarkIrpPending( Irp ); } // On the way up, pagable might become clear. Mimic the driver below us. if ( !FlagOn( deviceExtension->NextLowerDriver->Flags, DO_POWER_PAGABLE ) ) { ClearFlag( DeviceObject->Flags, DO_POWER_PAGABLE ); } IoReleaseRemoveLock( &deviceExtension->RemoveLock, Irp ); return STATUS_CONTINUE_COMPLETION; } __checkReturn NTSTATUS FilterDispatchPower( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ) { PDEVICE_EXTENSION deviceExtension; NTSTATUS status; deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension; status = IoAcquireRemoveLock( &deviceExtension->RemoveLock, Irp ); if ( !NT_SUCCESS( status ) ) { // may be device is being removed. Irp->IoStatus.Status = status; PoStartNextPowerIrp( Irp ); IoCompleteRequest( Irp, IO_NO_INCREMENT ); return status; } PoStartNextPowerIrp( Irp ); IoSkipCurrentIrpStackLocation( Irp ); status = PoCallDriver(deviceExtension->NextLowerDriver, Irp ); IoReleaseRemoveLock( &deviceExtension->RemoveLock, Irp ); return status; } VOID FilterUnload( __in PDRIVER_OBJECT DriverObject ) { ASSERT( !DriverObject->DeviceObject ); // We should not be unloaded until all the devices we control // have been removed from our queue. FilterDeleteControlObject(); ExDeleteResourceLite( &Globals.m_DeviceListLock ); return; } __checkReturn NTSTATUS FilterCreateControlObject ( __in PUNICODE_STRING RegistryPath, __in PDRIVER_OBJECT DriverObject ) { UNICODE_STRING ntDeviceName; UNICODE_STRING symbolicLinkName; PCONTROL_DEVICE_EXTENSION deviceExtension; NTSTATUS status = STATUS_UNSUCCESSFUL; UNICODE_STRING sddlString; // // Using unsafe function so that the IRQL remains at PASSIVE_LEVEL. // IoCreateDeviceSecure & IoCreateSymbolicLink must be called at // PASSIVE_LEVEL. // ExAcquireFastMutexUnsafe( &Globals.m_ControlMutex ); __try { // // If this is a first instance of the device, then create a controlobject // and register dispatch points to handle ioctls. // if ( 1 != ++Globals.m_InstanceCount ) { __leave; } RtlInitUnicodeString( &ntDeviceName, NTDEVICE_NAME_STRING ); RtlInitUnicodeString( &symbolicLinkName, SYMBOLIC_NAME_STRING ); status = IoCreateDevice ( DriverObject, sizeof( CONTROL_DEVICE_EXTENSION ), &ntDeviceName, FILE_DEVICE_UNKNOWN, 0, FALSE, &Globals.m_CDO ); if ( NT_SUCCESS( status ) ) { SetFlag( Globals.m_CDO->Flags, DO_BUFFERED_IO ); status = IoCreateSymbolicLink( &symbolicLinkName, &ntDeviceName ); if ( !NT_SUCCESS( status ) ) { IoDeleteDevice( Globals.m_CDO ); __leave; } deviceExtension = (PCONTROL_DEVICE_EXTENSION) Globals.m_CDO->DeviceExtension; deviceExtension->m_CommonData.Type = DEVICE_TYPE_CDO; deviceExtension->m_ControlData = NULL; deviceExtension->m_Deleted = FALSE; RtlZeroMemory ( &deviceExtension->m_usRegistryPath, sizeof( UNICODE_STRING ) ); deviceExtension->m_usRegistryPath.Buffer = (PWCH) ExAllocatePoolWithTag ( PagedPool, RegistryPath->Length, _ALLOC_TAG ); if ( deviceExtension->m_usRegistryPath.Buffer ) { deviceExtension->m_usRegistryPath.Length = 0; deviceExtension->m_usRegistryPath.MaximumLength = RegistryPath->MaximumLength; RtlCopyUnicodeString ( &deviceExtension->m_usRegistryPath, RegistryPath ); } ClearFlag( Globals.m_CDO->Flags, DO_DEVICE_INITIALIZING ); } } __finally { ExReleaseFastMutexUnsafe( &Globals.m_ControlMutex ); } return status; } VOID FilterDeleteControlObject ( ) { UNICODE_STRING symbolicLinkName; PCONTROL_DEVICE_EXTENSION deviceExtension; ExAcquireFastMutexUnsafe( &Globals.m_ControlMutex ); // // If this is the last instance of the device then delete the controlobject // and symbolic link to enable the pnp manager to unload the driver. // if ( !(--Globals.m_InstanceCount) && Globals.m_CDO ) { RtlInitUnicodeString( &symbolicLinkName, SYMBOLIC_NAME_STRING); deviceExtension = (PCONTROL_DEVICE_EXTENSION) Globals.m_CDO->DeviceExtension; deviceExtension->m_Deleted = TRUE; FREE_POOL( deviceExtension->m_usRegistryPath.Buffer ); IoDeleteSymbolicLink( &symbolicLinkName ); IoDeleteDevice( Globals.m_CDO ); Globals.m_CDO = NULL; } ExReleaseFastMutexUnsafe( &Globals.m_ControlMutex ); } __checkReturn BOOLEAN IsGetMediaSerialNmberRequest ( PIO_STACK_LOCATION IrpStack ) { if ( IRP_MJ_DEVICE_CONTROL != IrpStack->MajorFunction && IRP_MJ_INTERNAL_DEVICE_CONTROL != IrpStack->MajorFunction ) { return FALSE; } if ( IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER != IrpStack->Parameters.DeviceIoControl.IoControlCode ) { return FALSE; } return TRUE; } __checkReturn NTSTATUS FilterDispatchIo ( __in PDEVICE_OBJECT DeviceObject, __in PIRP Irp ) { PIO_STACK_LOCATION irpStack; NTSTATUS status; PCONTROL_DEVICE_EXTENSION deviceExtension; PCOMMON_DEVICE_DATA commonData; PVOID InputBuffer; PVOID OutputBuffer; ULONG InputBufferSize; ULONG OutputBufferSize; PIO_STATUS_BLOCK IoStatus; commonData = (PCOMMON_DEVICE_DATA) DeviceObject->DeviceExtension; IoStatus = &Irp->IoStatus; irpStack = IoGetCurrentIrpStackLocation( Irp ); InputBuffer = Irp->AssociatedIrp.SystemBuffer; InputBufferSize = irpStack->Parameters.DeviceIoControl.InputBufferLength; OutputBuffer = Irp->AssociatedIrp.SystemBuffer; OutputBufferSize = irpStack->Parameters.DeviceIoControl.OutputBufferLength; // // Please note that this is a common dispatch point for controlobject and // filter deviceobject attached to the pnp stack. // if ( commonData->Type == DEVICE_TYPE_FIDO ) { if ( IsGetMediaSerialNmberRequest( irpStack ) && InputBuffer && InputBufferSize >= sizeof( GET_MEDIA_SERIAL_NUMBER_GUID ) && IsEqualGUID ( *(PGUID) InputBuffer, GET_MEDIA_SERIAL_NUMBER_GUID ) ) { PDEVICE_EXTENSION pFiDoDevExt = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension; PDEVCTRL_DEVICEINFO pMedia = (PDEVCTRL_DEVICEINFO) OutputBuffer; PUNICODE_STRING pusDeviceType = &pFiDoDevExt->DevName.usDeviceType; ULONG retlength = sizeof( DEVCTRL_DEVICEINFO ) + pFiDoDevExt->DeviceId.Length + pusDeviceType->Length; if ( pMedia && OutputBufferSize >= retlength ) { status = STATUS_SUCCESS; Irp->IoStatus.Information = retlength; RtlZeroMemory( pMedia, retlength ); RtlCopyMemory ( pMedia->Data, pFiDoDevExt->DeviceId.Buffer, pFiDoDevExt->DeviceId.Length ); pMedia->IdOffset = FIELD_OFFSET( DEVCTRL_DEVICEINFO, Data ) ; pMedia->IdLenght = pFiDoDevExt->DeviceId.Length; pMedia->IsIdUnique = pFiDoDevExt->IsUnique; if ( pusDeviceType->Length ) { pMedia->ClassIdLength = pusDeviceType->Length; pMedia->ClassIdOffset = pMedia->IdOffset + pMedia->IdLenght; RtlCopyMemory ( Add2Ptr( pMedia, pMedia->ClassIdOffset ), pusDeviceType->Buffer, pusDeviceType->Length ); } } else { status = STATUS_INSUFFICIENT_RESOURCES; Irp->IoStatus.Information = 0; } Irp->IoStatus.Status = status; IoCompleteRequest ( Irp, IO_NO_INCREMENT ); return status; } // // We will just the request down as we are not interested in handling // requests that come on the PnP stack. // return FilterPass( DeviceObject, Irp ); } ASSERT( commonData->Type == DEVICE_TYPE_CDO ); deviceExtension = (PCONTROL_DEVICE_EXTENSION)DeviceObject->DeviceExtension; if ( !deviceExtension->m_Deleted ) { status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; irpStack = IoGetCurrentIrpStackLocation( Irp ); switch (irpStack->MajorFunction) { case IRP_MJ_CREATE: break; case IRP_MJ_CLOSE: break; case IRP_MJ_CLEANUP: break; #if DBG case IRP_MJ_DEVICE_CONTROL: #endif case IRP_MJ_INTERNAL_DEVICE_CONTROL: //switch (irpStack->Parameters.DeviceIoControl.IoControlCode) break; default: break; } } else { ASSERTMSG( FALSE, "Requests being sent to a dead device\n" ); status = STATUS_DEVICE_REMOVED; } Irp->IoStatus.Status = status; IoCompleteRequest( Irp, IO_NO_INCREMENT ); return status; }
[ [ [ 1, 1547 ] ] ]
ab1397df3f0d069b53f421c4ac4e20008160fd29
e5253d575f7a65d383fd04c129591df4d97eb8ef
/Geometry/Teste.h
0d7b8eedff077ccba8783701fe688dd9cd20e23a
[]
no_license
ly774508966/Objective-ART2
e93fd3567307b321155e1c00e989669e8348a1be
b16fb8dc6fda19fa8042bf45c68412f27c1a8dbb
refs/heads/master
2021-01-19T08:28:54.796636
2011-10-19T19:54:03
2011-10-19T19:54:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,303
h
#pragma once using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Diagnostics; namespace Geometry { /// <summary> /// Summary for Teste /// </summary> public ref class Teste : public System::ComponentModel::Component { public: Teste(void) { InitializeComponent(); // //TODO: Add the constructor code here // } Teste(System::ComponentModel::IContainer ^container) { /// <summary> /// Required for Windows.Forms Class Composition Designer support /// </summary> container->Add(this); InitializeComponent(); } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~Teste() { if (components) { delete components; } } private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { components = gcnew System::ComponentModel::Container(); } #pragma endregion }; }
[ [ [ 1, 63 ] ] ]
08e8b79e6ec3262e3f1ebb8917779c3f1a70111a
d9a78f212155bb978f5ac27d30eb0489bca87c3f
/PB/src/PbRpc/rpcconnection.h
e2090710c71862f93c908e685befd7de99cfde43
[]
no_license
marchon/pokerbridge
1ed4a6a521f8644dcd0b6ec66a1ac46879b8473c
97d42ef318bf08f3bc0c0cb1d95bd31eb2a3a8a9
refs/heads/master
2021-01-10T07:15:26.496252
2010-05-17T20:01:29
2010-05-17T20:01:29
36,398,892
0
0
null
null
null
null
UTF-8
C++
false
false
1,929
h
#ifndef RpcConnection_H #define RpcConnection_H //#include <QObject> class RpcListener; class RpcChannel; #include "rpcurl.h" #include "rpcadaptor.h" class PB_EXPORT RpcConnection : public QObject { Q_OBJECT public: RpcConnection(QObject *parent = 0); ~RpcConnection(); // registers object void registerObject(const QString &path, QObject *obj); void registerProxy(const QString &path, QObject *obj); static RpcConnection *instance(); RpcAdaptor *findObject(const QString &path); RpcAdaptor *findProxy(const QString &path); bool invoke(QObject *self, const QString &remote, const QByteArray &method, const QList<QVariant> &args); void dumpObjects(); const RpcUrl &remoteSender(); QString localHost(); // called by RpcAdaptor public: bool remoteCall(const RpcUrl &path, const QByteArray &method, const QList<QVariant> &args, const QString &senderPath); bool remoteSignal(const QByteArray &signal, const QList<QVariant> &args, const QString &senderPath); // called by RpcChannel void channelConnected(RpcChannel *chan); void chanelDisconnected(RpcChannel *chan); void channelSignal(const QByteArray &signal, const QList<QVariant> &args, const RpcUrl &senderUrl); void channelCall(const RpcUrl &path, const QByteArray &method, const QList<QVariant> &args, const RpcUrl &senderUrl); // implementation (tcp) void setListener(RpcListener *list); bool listenTcp(uint port); bool connectTcp(QString host, uint port); // notify all about channels signals: void disconnected(RpcChannel *chan); void connected(RpcChannel *chan); protected: QString _localHost; int _localPort; QMap<QString, QPointer<RpcAdaptor>> _objects; // path->adaptor QMap<QString, QPointer<RpcChannel>> _channels; // host->channel RpcUrl _remoteSender; QPointer<RpcListener> _listener; static QPointer<RpcConnection> _instance; }; #endif // RpcConnection_H
[ "[email protected]", "mikhail.mitkevich@a5377438-2eb2-11df-b28a-19025b8c0740" ]
[ [ [ 1, 7 ], [ 11, 18 ], [ 20, 20 ], [ 22, 22 ], [ 25, 27 ], [ 30, 30 ], [ 42, 42 ], [ 47, 47 ], [ 49, 49 ], [ 59, 59 ], [ 61, 63 ] ], [ [ 8, 10 ], [ 19, 19 ], [ 21, 21 ], [ 23, 24 ], [ 28, 29 ], [ 31, 41 ], [ 43, 46 ], [ 48, 48 ], [ 50, 58 ], [ 60, 60 ] ] ]
89648fa70b4dc2e7c1a4a633b397e814372d7013
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/wave/test/testwave/testfiles/t_6_006.cpp
627a77295e4cebcb4156d7323e05aa7137d655c6
[ "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
2,403
cpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001-2009 Hartmut Kaiser. 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) The tests included in this file were initially taken from the mcpp V2.5 preprocessor validation suite and were modified to fit into the Boost.Wave unit test requirements. The original files of the mcpp preprocessor are distributed under the license reproduced at the end of this file. =============================================================================*/ // Tests error reporting: illegal #if expressions. #define A 1 #define B 1 // 14.2: Operators =, +=, ++, etc. are not allowed in #if expression. //E t_6_006.cpp(23): error: ill formed preprocessor expression: 1.1 #if A.B #endif /*- * Copyright (c) 1998, 2002-2005 Kiyoshi Matsui <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */
[ "metrix@Blended.(none)" ]
[ [ [ 1, 51 ] ] ]
febbc3b77cc7399510ea912a1a097d98da8a4b6a
584d088c264ac58050ed0757b08d032b6c7fc83b
/oldGUI/GUI_Slide.cpp
493a624460288b418070d27cfa10df677506aa20
[]
no_license
littlewingsoft/lunaproject
a843ca37c04bdc4e1e4e706381043def1789ab39
9102a39deaad74b2d73ee0ec3354f37f6f85702f
refs/heads/master
2020-05-30T15:21:20.515967
2011-02-04T18:41:43
2011-02-04T18:41:43
32,302,109
0
0
null
null
null
null
UHC
C++
false
false
6,306
cpp
#include "stdafx.h" CGUI_Slide* CGUI_Slide::_pCurrentDownSlide = NULL; CGUI_Slide::CGUI_Slide(void):CGUI_Button() { _Style=HORIZON; } CGUI_Slide::~CGUI_Slide(void) { } int CGUI_Slide::GetRate(){ return _Rate; } void CGUI_Slide::SetRate(int rate) { if( rate<0) rate = 0; if( rate>100) rate = 100; _Rate = rate; float frate = rate / 100.0f; IGUI_Object* pObj = GetParent(); float result=pObj->GetX()+this->_AllowRegion_Start+ ( _AllowRegion_End- _AllowRegion_Start-GetWidth())*frate; SetX( result ); CGUI_MGR::_SendMessage( GUIMSG_SCROLL_HORIZON_DRAG,(DWORD)this,_Rate ); // 자기 최고 부모가 있다면 찾아서 이벤트 통지 IGUI_Object* pParent1 = GetSuperParent(); if( pParent1 != NULL ) CGUI_MGR::_SendMessage( pParent1->GetName(), GUIMSG_SCROLL_HORIZON_DRAG,(DWORD)this,_Rate );//m_Event } bool CGUI_Slide::ProcMessage(GUIMSG& Msg) { // 비활성화된 상태라면 GUIMSG_ENABLE를 제외하고 모두 반사 if( m_State == INACTIVE && Msg.dwMsg != GUIMSG_ENABLE ) return false; switch ( Msg.dwMsg ) { case GUIMSG_CREATED: { } return true; case GUIMSG_DISABLE: { m_State = INACTIVE; } return true; case GUIMSG_DESTROY: { } return true; case GUIMSG_CLOSE: { //CGUI_MGR::NoneFocusSetting(); DestroyAllChild(); } return false; case GUIMSG_DRAG: { // 실제 마우스 위치로 스크롤 바 영역의 100 분율기준 위치를 구하고 // 그 100분율 기준을 실제 스크롤 바로 환산 적용한다. 이부분은 되어 있으므로 // 스크롤바 영역에서의 100분율 위치만 구해줌. // 체크 기준은 버튼의 영역 내부이거나 이전에 눌린 기억이 있다면 오케이 int mousex = Msg.dwParam1; int mousey = Msg.dwParam2; POINT pt={mousex,mousey}; RECT rt={m_DestRect.left,m_DestRect.top,m_DestRect.right,m_DestRect.bottom}; if(_pCurrentDownSlide != this ) return false; if( m_State != DOWN && PtInRect(&rt,pt) == FALSE ) return false; int relativex = GetX(); IGUI_Object* pParent = GetParent(); if( pParent ) relativex = GetX() - pParent->GetX(); float Bar_X = relativex - _AllowRegion_Start; float Bar_Width = GetWidth(); float newx = 0.0f; float Enable_Region = (_AllowRegion_End -_AllowRegion_Start)-GetWidth(); DWORD PointRate = (Bar_X/Enable_Region) *100.0f; int intervalx = this->GetFirstClick().x; int x =int( mousex - intervalx ); // 간격을 유지해줘야 합니다. if( x < pParent->GetX()+_AllowRegion_Start )// 는 같거나 커야 하고 { x = int(pParent->GetX()+_AllowRegion_Start); } else if( x+Bar_Width>= pParent->GetX() + _AllowRegion_End ) { x = pParent->GetX()+_AllowRegion_End - Bar_Width; } SetX( float(x) ); //m_BoundRect.top+ // 포인트를 움직였으므로 // 스크롤이 움직인 만큼 영향을 준다. // 포인트가 움직일수 있는 영역은 전체 DESTRECT 에서 위아래 각각 point_Height /2 한 만큼 이다. // 그만큼을 이동가능한 영역의 전체로 보고 현재 위치는 전체에서의 상대적인 위치의 2048 분율로 한다. // 2의 승수 승이므로 / 연산시 소숫점 5자리 까지는 오차가 생기지 않음 // 현재 마우스 위치???? 드레그 시에는 100분율로 역시 이동함... _Rate = PointRate; CGUI_MGR::_SendMessage( GUIMSG_SCROLL_HORIZON_DRAG,(DWORD)this,PointRate ); // 자기 최고 부모가 있다면 찾아서 이벤트 통지 IGUI_Object* pParent1 = GetSuperParent(); if( pParent1 != NULL ) CGUI_MGR::_SendMessage( pParent1->GetName(), GUIMSG_SCROLL_HORIZON_DRAG,(DWORD)this,PointRate );//m_Event } return true; case GUIMSG_MLDOWN: { POINT pt={g_MouseMGR.GetX(),g_MouseMGR.GetY() }; // 현재 이동가능 영역안에 있다면 버튼을 움직여 버려 _pCurrentDownSlide = this; bool bInSpace = false; IGUI_Object* pSuper = GetSuperParent(); int regionx = 0; int regiony = 0; if( pSuper) { regionx = pSuper->GetX(); } RECT rt0 = { regionx+_AllowRegion_Start, m_DestRect.top, regionx+_AllowRegion_End,m_DestRect.bottom } ; if( PtInRect( &rt0,pt) ) { // 마우스 위치는 이동버튼의 중간위치 이며 // 중간이상의 위치면 그 차이만큼이 위치가 된다 ( 써글 ) float half = (GetWidth()/2); float res = pt.x; if( res-half < rt0.left ) res = (rt0.left ) ; else if( res+GetWidth() > rt0.right ) res = rt0.right - GetWidth(); else res -= half; SetX( res ); bInSpace = true; } RECT rt = { m_DestRect.left,m_DestRect.top,m_DestRect.right,m_DestRect.bottom }; if( PtInRect( &rt, pt ) || bInSpace ) { CGUI_MGR::SetGuiFocus( m_Name ); // 부모에게 포커스를 준다. m_FirstClick.x = pt.x - m_BoundRect.left; m_FirstClick.y = pt.y - m_BoundRect.top ; m_State = DOWN; g_sndmgr.Play( "SND_CLICK" ); GUIMSG msg; msg.dwMsg = GUIMSG_DRAG; msg.dwParam1 = pt.x ; msg.dwParam2 = pt.y; this->ProcMessage(msg); return true; } } break; case GUIMSG_MLUP: { _pCurrentDownSlide = NULL; POINT pt={g_MouseMGR.GetX(),g_MouseMGR.GetY() }; RECT rt = { m_DestRect.left,m_DestRect.top,m_DestRect.right,m_DestRect.bottom }; if( PtInRect( &rt, pt ) ) { m_State = FOCUSON; //if( IsEvent() == true ) //{ // CGUI_MGR::_SendMessage( GUIMSG_SCROLL_HORIZON_DRAG,(DWORD)this,0 );//m_Event // // 자기 최고 부모가 있다면 찾아서 이벤트 통지 // IGUI_Object* pParent = GetSuperParent(); // if( pParent != NULL ) // CGUI_MGR::_SendMessage( pParent->GetName(), GUIMSG_SCROLL_HORIZON_DRAG,(DWORD)this,0 );//m_Event //} return true; }else m_State = NORMAL; }break; } return false; } void CGUI_Slide::Render() { if( m_Img.TexID != -1 ) { RECT tmp={m_DestRect.left,m_DestRect.top, m_DestRect.right,m_DestRect.bottom }; g_D3D.BltSprite( m_Layer ,m_Img.TexID, NULL, tmp, m_Clr, D3D_NORMALSTATE); //D3D_ALPHASTATE //D3D_INTERFACE_LAYER0 } }
[ "jungmoona@2e9c511a-93cf-11dd-bb0a-adccfa6872b9" ]
[ [ [ 1, 207 ] ] ]
1581322feb092c1bbcbb2c422c1abeef3e003a0f
a0d4f557ddaf4351957e310478e183dac45d77a1
/src/Script/ScriptGroupDoor.h
05376a27e1c13a94638e1199296886e96c5207b9
[]
no_license
houpcz/Houp-s-level-editor
1f6216e8ad8da393e1ee151e36fc37246279bfed
c762c9f5ed064ba893bf34887293a73dd35a06f8
refs/heads/master
2016-09-11T11:03:34.560524
2011-08-09T11:37:49
2011-08-09T11:37:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
804
h
#ifndef _SCRIPTGROUPDOOR_H_ #define _SCRIPTGROUPDOOR_H_ class C_ScriptGroupDoor : public C_Door { private : C_Button bNew; // nova skupina vector<C_Input> inputGroup; // editovatelne nazvy skupin skriptu vector<C_InputInteger> inputParent; C_ButtonGroup bDel; // na smazani dane skupiny, ti co prijdou o skupinu, ujme se o ne rodic skupiny C_ButtonGroup bActiveGroup; public : C_ScriptGroupDoor(FILE * fr) {Load(fr);}; C_ScriptGroupDoor(int n_x, int n_y, int n_width, int n_height, string n_title); ~C_ScriptGroupDoor() {}; void DrawContent(); void DoorEverTime(); void DoorActionDown(int button); void FirstTime(); void MakeContent(); }; #endif
[ [ [ 1, 23 ] ] ]
3be3937860cb136fe6ea783be56195375ca1fd94
a7109719291d3fb1e3dabfed9405d2b340ad8a89
/Gandhi-Prototype/include/cAStar.h
dc56027ac14c303c54354bd70d122197e350f10d
[]
no_license
edufg88/gandhi-prototype
0ea3c6a7bbe72b6d382fa76f23c40b4a0280c666
947f2c6d8a63421664eb5018d5d01b8da71f46a2
refs/heads/master
2021-01-01T17:32:40.791045
2011-12-19T20:10:34
2011-12-19T20:10:34
32,288,341
0
0
null
null
null
null
UTF-8
C++
false
false
2,236
h
#ifndef __ASTAR_H__ #define __ASTAR_H__ #include "cScene.h" #define mapWidth AREA_WIDTH #define mapHeight AREA_HEIGHT #define numberPeople 3 class cAStar { private: //Declare constants int tileSize; int onClosedList; int notfinished, notStarted;// path-related constants int found, nonexistent; int walkable, unwalkable;// walkability array constants //Create needed arrays char walkability [mapWidth][mapHeight]; int openList[mapWidth*mapHeight+2]; //1 dimensional array holding ID# of open list items int whichList[mapWidth+1][mapHeight+1]; //2 dimensional array used to record //whether a cell is on the open list or on the closed list. int openX[mapWidth*mapHeight+2]; //1d array stores the x location of an item on the open list int openY[mapWidth*mapHeight+2]; //1d array stores the y location of an item on the open list int parentX[mapWidth+1][mapHeight+1]; //2d array to store parent of each cell (x) int parentY[mapWidth+1][mapHeight+1]; //2d array to store parent of each cell (y) int Fcost[mapWidth*mapHeight+2]; //1d array to store F cost of a cell on the open list int Gcost[mapWidth+1][mapHeight+1]; //2d array to store G cost for each cell. int Hcost[mapWidth*mapHeight+2]; //1d array to store H cost of a cell on the open list int pathLength[numberPeople+1]; //stores length of the found path for critter int pathLocation[numberPeople+1]; //stores current position along the chosen path for critter int *pathBank [numberPeople+1]; //Path reading variables int pathStatus[numberPeople+1]; int xPath[numberPeople+1]; int yPath[numberPeople+1]; public: cAStar(); virtual ~cAStar(); void InitializePathfinder(void); void EndPathfinder(void); int FindPath (int pathfinderID,int startingX, int startingY, int targetX, int targetY); void ReadPath(int pathfinderID,int currentX,int currentY, int pixelsPerFrame); int ReadPathX(int pathfinderID,int pathLocation); int ReadPathY(int pathfinderID,int pathLocation); ///////////////////////////////// void LoadMap(); void PrintPath(); void NextCell(int *cx,int *cy); private: int idxStep; cScene *Scene; ///////////////////////////////// }; #endif
[ "[email protected]@5f958858-fb9a-a521-b75c-3c5ff6351dd8" ]
[ [ [ 1, 64 ] ] ]
a8adf9d1adf4030cec7d132b49f672c9462d0641
f8b364974573f652d7916c3a830e1d8773751277
/emulator/allegrex/instructions/SUBU.h
ef013089d34aa5d965f99e52f007abac28f95dd5
[]
no_license
lemmore22/pspe4all
7a234aece25340c99f49eac280780e08e4f8ef49
77ad0acf0fcb7eda137fdfcb1e93a36428badfd0
refs/heads/master
2021-01-10T08:39:45.222505
2009-08-02T11:58:07
2009-08-02T11:58:07
55,047,469
0
0
null
null
null
null
UTF-8
C++
false
false
1,035
h
template< > struct AllegrexInstructionTemplate< 0x00000023, 0xfc0007ff > : AllegrexInstructionUnknown { static AllegrexInstructionTemplate &self() { static AllegrexInstructionTemplate insn; return insn; } static AllegrexInstruction *get_instance() { return &AllegrexInstructionTemplate::self(); } virtual AllegrexInstruction *instruction(u32 opcode) { return this; } virtual char const *opcode_name() { return "SUBU"; } virtual void interpret(Processor &processor, u32 opcode); virtual void disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment); protected: AllegrexInstructionTemplate() {} }; typedef AllegrexInstructionTemplate< 0x00000023, 0xfc0007ff > AllegrexInstruction_SUBU; namespace Allegrex { extern AllegrexInstruction_SUBU &SUBU; } #ifdef IMPLEMENT_INSTRUCTION AllegrexInstruction_SUBU &Allegrex::SUBU = AllegrexInstruction_SUBU::self(); #endif
[ [ [ 1, 41 ] ] ]
bf662598ac6cc0f2c3676d460dbabba30c908109
8a2e417c772eba9cf4653d0c688dd3ac96590964
/prop-src/setl-ast.h
7bda744b614d0ed183c07240da0e2a0ca53ca263
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
romix/prop-cc
1a190ba6ed8922428352826de38efb736e464f50
3f7f2e4a4d0b717f4e4f3dbd4c7f9d1f35572f8f
refs/heads/master
2023-08-30T12:55:00.192286
2011-07-19T20:56:39
2011-07-19T20:56:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,332
h
/////////////////////////////////////////////////////////////////////////////// // This file is generated automatically using Prop (version 2.4.0), // last updated on Jul 1, 2011. // The original source file is "..\..\prop-src\setl-ast.ph". /////////////////////////////////////////////////////////////////////////////// #line 1 "../../prop-src/setl-ast.ph" /////////////////////////////////////////////////////////////////////////////// // // This file contains the abstract syntax tree definitions for the // SETL-like extension language of Prop. // /////////////////////////////////////////////////////////////////////////////// #ifndef setl_extension_abstract_syntax_tree_h #define setl_extension_abstract_syntax_tree_h #include <iostream> #include "basics.h" #include "ir.h" /////////////////////////////////////////////////////////////////////////////// // // Forward AST declarations. // /////////////////////////////////////////////////////////////////////////////// #line 22 "../../prop-src/setl-ast.ph" #line 26 "../../prop-src/setl-ast.ph" /////////////////////////////////////////////////////////////////////////////// // // Forward class definition for Exp // /////////////////////////////////////////////////////////////////////////////// #ifndef datatype_Exp_defined #define datatype_Exp_defined class a_Exp; typedef a_Exp * Exp; #endif /////////////////////////////////////////////////////////////////////////////// // // Forward class definition for Decl // /////////////////////////////////////////////////////////////////////////////// #ifndef datatype_Decl_defined #define datatype_Decl_defined class a_Decl; typedef a_Decl * Decl; #endif /////////////////////////////////////////////////////////////////////////////// // // Forward class definition for Time // /////////////////////////////////////////////////////////////////////////////// #ifndef datatype_Time_defined #define datatype_Time_defined class a_Time; typedef a_Time * Time; #endif /////////////////////////////////////////////////////////////////////////////// // // Forward class definition for Space // /////////////////////////////////////////////////////////////////////////////// #ifndef datatype_Space_defined #define datatype_Space_defined class a_Space; typedef a_Space * Space; #endif #line 26 "../../prop-src/setl-ast.ph" #line 26 "../../prop-src/setl-ast.ph" /////////////////////////////////////////////////////////////////////////////// // // AST for definitions, signatures, statements and bindings // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // // Type 'Def' represents definitions. // /////////////////////////////////////////////////////////////////////////////// #line 40 "../../prop-src/setl-ast.ph" #line 116 "../../prop-src/setl-ast.ph" /////////////////////////////////////////////////////////////////////////////// // // Forward class definition for Def // /////////////////////////////////////////////////////////////////////////////// #ifndef datatype_Def_defined #define datatype_Def_defined class a_Def; typedef a_Def * Def; #endif # define v_NOdef 0 # define NOdef (Def)v_NOdef /////////////////////////////////////////////////////////////////////////////// // // Forward class definition for Sig // /////////////////////////////////////////////////////////////////////////////// #ifndef datatype_Sig_defined #define datatype_Sig_defined class a_Sig; typedef a_Sig * Sig; #endif # define v_NOsig 0 # define NOsig (Sig)v_NOsig /////////////////////////////////////////////////////////////////////////////// // // Forward class definition for Stmt // /////////////////////////////////////////////////////////////////////////////// #ifndef datatype_Stmt_defined #define datatype_Stmt_defined class a_Stmt; typedef a_Stmt * Stmt; #endif # define v_NOstmt 0 # define NOstmt (Stmt)v_NOstmt /////////////////////////////////////////////////////////////////////////////// // Definition of type LabSig /////////////////////////////////////////////////////////////////////////////// #line 110 "../../prop-src/setl-ast.ph" typedef struct { Id id; Sig sig; } LabSig; /////////////////////////////////////////////////////////////////////////////// // Definition of type LabSigs /////////////////////////////////////////////////////////////////////////////// #line 111 "../../prop-src/setl-ast.ph" typedef a_List<LabSig> * LabSigs; /////////////////////////////////////////////////////////////////////////////// // Definition of type Defs /////////////////////////////////////////////////////////////////////////////// #line 112 "../../prop-src/setl-ast.ph" typedef a_List<Def> * Defs; /////////////////////////////////////////////////////////////////////////////// // Definition of type Sigs /////////////////////////////////////////////////////////////////////////////// #line 113 "../../prop-src/setl-ast.ph" typedef a_List<Sig> * Sigs; /////////////////////////////////////////////////////////////////////////////// // Definition of type Stmts /////////////////////////////////////////////////////////////////////////////// #line 114 "../../prop-src/setl-ast.ph" typedef a_List<Stmt> * Stmts; /////////////////////////////////////////////////////////////////////////////// // Definition of type Generators /////////////////////////////////////////////////////////////////////////////// #line 115 "../../prop-src/setl-ast.ph" typedef a_List<Generator> * Generators; /////////////////////////////////////////////////////////////////////////////// // // Base class for datatype Def // /////////////////////////////////////////////////////////////////////////////// class a_Def : public Loc { public: enum Tag_Def { tag_VARdef = 0, tag_FUNCTIONdef = 1, tag_MODULEdef = 2, tag_SIGNATUREdef = 3, tag_TYPEdef = 4, tag_LAMBDAdef = 5 }; public: const Tag_Def tag__; // variant tag protected: inline a_Def(Tag_Def t__) : tag__(t__) {} public: }; inline int boxed(const a_Def * x) { return x != 0; } inline int untag(const a_Def * x) { return x ? (x->tag__+1) : 0; } /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Def::VARdef // /////////////////////////////////////////////////////////////////////////////// class Def_VARdef : public a_Def { public: #line 42 "../../prop-src/setl-ast.ph" Id id; Ty ty; Exp init_exp; inline Def_VARdef (Id x_id, Ty x_ty, Exp x_init_exp = NOexp) : a_Def(tag_VARdef), id(x_id), ty(x_ty), init_exp(x_init_exp) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Def::FUNCTIONdef // /////////////////////////////////////////////////////////////////////////////// class Def_FUNCTIONdef : public a_Def { public: #line 48 "../../prop-src/setl-ast.ph" Id id; LabTys args; Ty return_ty; Defs local_defs; Stmts body; inline Def_FUNCTIONdef (Id x_id, LabTys x_args, Ty x_return_ty, Defs x_local_defs, Stmts x_body) : a_Def(tag_FUNCTIONdef), id(x_id), args(x_args), return_ty(x_return_ty), local_defs(x_local_defs), body(x_body) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Def::MODULEdef // /////////////////////////////////////////////////////////////////////////////// class Def_MODULEdef : public a_Def { public: #line 56 "../../prop-src/setl-ast.ph" Id id; LabSigs args; Sig sig; Defs body; inline Def_MODULEdef (Id x_id, LabSigs x_args, Sig x_sig, Defs x_body) : a_Def(tag_MODULEdef), id(x_id), args(x_args), sig(x_sig), body(x_body) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Def::SIGNATUREdef // /////////////////////////////////////////////////////////////////////////////// class Def_SIGNATUREdef : public a_Def { public: #line 63 "../../prop-src/setl-ast.ph" Id id; LabSigs args; Sig sig; inline Def_SIGNATUREdef (Id x_id, LabSigs x_args, Sig x_sig) : a_Def(tag_SIGNATUREdef), id(x_id), args(x_args), sig(x_sig) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Def::TYPEdef // /////////////////////////////////////////////////////////////////////////////// class Def_TYPEdef : public a_Def { public: #line 69 "../../prop-src/setl-ast.ph" Decl TYPEdef; inline Def_TYPEdef (Decl x_TYPEdef) : a_Def(tag_TYPEdef), TYPEdef(x_TYPEdef) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Def::LAMBDAdef // /////////////////////////////////////////////////////////////////////////////// class Def_LAMBDAdef : public a_Def { public: #line 70 "../../prop-src/setl-ast.ph" LabTys _1; Defs _2; inline Def_LAMBDAdef (LabTys x_1, Defs x_2) : a_Def(tag_LAMBDAdef), _1(x_1), _2(x_2) { } }; /////////////////////////////////////////////////////////////////////////////// // // Datatype constructor functions for Def // /////////////////////////////////////////////////////////////////////////////// inline a_Def * VARdef (Id x_id, Ty x_ty, Exp x_init_exp = NOexp) { return new Def_VARdef (x_id, x_ty, x_init_exp); } inline a_Def * FUNCTIONdef (Id x_id, LabTys x_args, Ty x_return_ty, Defs x_local_defs, Stmts x_body) { return new Def_FUNCTIONdef (x_id, x_args, x_return_ty, x_local_defs, x_body); } inline a_Def * MODULEdef (Id x_id, LabSigs x_args, Sig x_sig, Defs x_body) { return new Def_MODULEdef (x_id, x_args, x_sig, x_body); } inline a_Def * SIGNATUREdef (Id x_id, LabSigs x_args, Sig x_sig) { return new Def_SIGNATUREdef (x_id, x_args, x_sig); } inline a_Def * TYPEdef (Decl x_TYPEdef) { return new Def_TYPEdef (x_TYPEdef); } inline a_Def * LAMBDAdef (LabTys x_1, Defs x_2) { return new Def_LAMBDAdef (x_1, x_2); } /////////////////////////////////////////////////////////////////////////////// // // Downcasting functions for Def // /////////////////////////////////////////////////////////////////////////////// inline Def_VARdef * _VARdef(const a_Def * _x_) { return (Def_VARdef *)_x_; } inline Def_FUNCTIONdef * _FUNCTIONdef(const a_Def * _x_) { return (Def_FUNCTIONdef *)_x_; } inline Def_MODULEdef * _MODULEdef(const a_Def * _x_) { return (Def_MODULEdef *)_x_; } inline Def_SIGNATUREdef * _SIGNATUREdef(const a_Def * _x_) { return (Def_SIGNATUREdef *)_x_; } inline Def_TYPEdef * _TYPEdef(const a_Def * _x_) { return (Def_TYPEdef *)_x_; } inline Def_LAMBDAdef * _LAMBDAdef(const a_Def * _x_) { return (Def_LAMBDAdef *)_x_; } /////////////////////////////////////////////////////////////////////////////// // // Base class for datatype Sig // /////////////////////////////////////////////////////////////////////////////// class a_Sig : public Loc { public: enum Tag_Sig { tag_IDsig = 0, tag_DOTsig = 1, tag_APPsig = 2, tag_DEFsig = 3, tag_LAMBDAsig = 4 }; public: const Tag_Sig tag__; // variant tag protected: inline a_Sig(Tag_Sig t__) : tag__(t__) {} public: }; inline int boxed(const a_Sig * x) { return x != 0; } inline int untag(const a_Sig * x) { return x ? (x->tag__+1) : 0; } /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Sig::IDsig // /////////////////////////////////////////////////////////////////////////////// class Sig_IDsig : public a_Sig { public: #line 80 "../../prop-src/setl-ast.ph" Id IDsig; inline Sig_IDsig (Id x_IDsig) : a_Sig(tag_IDsig), IDsig(x_IDsig) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Sig::DOTsig // /////////////////////////////////////////////////////////////////////////////// class Sig_DOTsig : public a_Sig { public: #line 81 "../../prop-src/setl-ast.ph" Sig _1; Id _2; inline Sig_DOTsig (Sig x_1, Id x_2) : a_Sig(tag_DOTsig), _1(x_1), _2(x_2) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Sig::APPsig // /////////////////////////////////////////////////////////////////////////////// class Sig_APPsig : public a_Sig { public: #line 82 "../../prop-src/setl-ast.ph" Sig _1; Sigs _2; inline Sig_APPsig (Sig x_1, Sigs x_2) : a_Sig(tag_APPsig), _1(x_1), _2(x_2) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Sig::DEFsig // /////////////////////////////////////////////////////////////////////////////// class Sig_DEFsig : public a_Sig { public: #line 83 "../../prop-src/setl-ast.ph" Defs DEFsig; inline Sig_DEFsig (Defs x_DEFsig) : a_Sig(tag_DEFsig), DEFsig(x_DEFsig) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Sig::LAMBDAsig // /////////////////////////////////////////////////////////////////////////////// class Sig_LAMBDAsig : public a_Sig { public: #line 84 "../../prop-src/setl-ast.ph" LabSigs _1; Sig _2; inline Sig_LAMBDAsig (LabSigs x_1, Sig x_2) : a_Sig(tag_LAMBDAsig), _1(x_1), _2(x_2) { } }; /////////////////////////////////////////////////////////////////////////////// // // Datatype constructor functions for Sig // /////////////////////////////////////////////////////////////////////////////// inline a_Sig * IDsig (Id x_IDsig) { return new Sig_IDsig (x_IDsig); } inline a_Sig * DOTsig (Sig x_1, Id x_2) { return new Sig_DOTsig (x_1, x_2); } inline a_Sig * APPsig (Sig x_1, Sigs x_2) { return new Sig_APPsig (x_1, x_2); } inline a_Sig * DEFsig (Defs x_DEFsig) { return new Sig_DEFsig (x_DEFsig); } inline a_Sig * LAMBDAsig (LabSigs x_1, Sig x_2) { return new Sig_LAMBDAsig (x_1, x_2); } /////////////////////////////////////////////////////////////////////////////// // // Downcasting functions for Sig // /////////////////////////////////////////////////////////////////////////////// inline Sig_IDsig * _IDsig(const a_Sig * _x_) { return (Sig_IDsig *)_x_; } inline Sig_DOTsig * _DOTsig(const a_Sig * _x_) { return (Sig_DOTsig *)_x_; } inline Sig_APPsig * _APPsig(const a_Sig * _x_) { return (Sig_APPsig *)_x_; } inline Sig_DEFsig * _DEFsig(const a_Sig * _x_) { return (Sig_DEFsig *)_x_; } inline Sig_LAMBDAsig * _LAMBDAsig(const a_Sig * _x_) { return (Sig_LAMBDAsig *)_x_; } /////////////////////////////////////////////////////////////////////////////// // // Base class for datatype Stmt // /////////////////////////////////////////////////////////////////////////////// class a_Stmt : public Loc { public: enum Tag_Stmt { tag_ASSIGNstmt = 0, tag_BLOCKstmt = 1, tag_WHILEstmt = 2, tag_IFstmt = 3, tag_MATCHstmt = 4, tag_REWRITEstmt = 5, tag_REPLACEMENTstmt = 6, tag_FORALLstmt = 7, tag_RETURNstmt = 8 }; public: const Tag_Stmt tag__; // variant tag protected: inline a_Stmt(Tag_Stmt t__) : tag__(t__) {} public: }; inline int boxed(const a_Stmt * x) { return x != 0; } inline int untag(const a_Stmt * x) { return x ? (x->tag__+1) : 0; } /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Stmt::ASSIGNstmt // /////////////////////////////////////////////////////////////////////////////// class Stmt_ASSIGNstmt : public a_Stmt { public: #line 94 "../../prop-src/setl-ast.ph" Exp _1; Exp _2; inline Stmt_ASSIGNstmt (Exp x_1, Exp x_2) : a_Stmt(tag_ASSIGNstmt), _1(x_1), _2(x_2) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Stmt::BLOCKstmt // /////////////////////////////////////////////////////////////////////////////// class Stmt_BLOCKstmt : public a_Stmt { public: #line 95 "../../prop-src/setl-ast.ph" Defs _1; Stmts _2; inline Stmt_BLOCKstmt (Defs x_1, Stmts x_2) : a_Stmt(tag_BLOCKstmt), _1(x_1), _2(x_2) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Stmt::WHILEstmt // /////////////////////////////////////////////////////////////////////////////// class Stmt_WHILEstmt : public a_Stmt { public: #line 96 "../../prop-src/setl-ast.ph" Exp _1; Stmt _2; inline Stmt_WHILEstmt (Exp x_1, Stmt x_2) : a_Stmt(tag_WHILEstmt), _1(x_1), _2(x_2) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Stmt::IFstmt // /////////////////////////////////////////////////////////////////////////////// class Stmt_IFstmt : public a_Stmt { public: #line 97 "../../prop-src/setl-ast.ph" Exp _1; Stmt _2; Stmt _3; inline Stmt_IFstmt (Exp x_1, Stmt x_2, Stmt x_3) : a_Stmt(tag_IFstmt), _1(x_1), _2(x_2), _3(x_3) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Stmt::MATCHstmt // /////////////////////////////////////////////////////////////////////////////// class Stmt_MATCHstmt : public a_Stmt { public: #line 98 "../../prop-src/setl-ast.ph" Decl MATCHstmt; inline Stmt_MATCHstmt (Decl x_MATCHstmt) : a_Stmt(tag_MATCHstmt), MATCHstmt(x_MATCHstmt) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Stmt::REWRITEstmt // /////////////////////////////////////////////////////////////////////////////// class Stmt_REWRITEstmt : public a_Stmt { public: #line 99 "../../prop-src/setl-ast.ph" Decl REWRITEstmt; inline Stmt_REWRITEstmt (Decl x_REWRITEstmt) : a_Stmt(tag_REWRITEstmt), REWRITEstmt(x_REWRITEstmt) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Stmt::REPLACEMENTstmt // /////////////////////////////////////////////////////////////////////////////// class Stmt_REPLACEMENTstmt : public a_Stmt { public: #line 100 "../../prop-src/setl-ast.ph" Decl REPLACEMENTstmt; inline Stmt_REPLACEMENTstmt (Decl x_REPLACEMENTstmt) : a_Stmt(tag_REPLACEMENTstmt), REPLACEMENTstmt(x_REPLACEMENTstmt) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Stmt::FORALLstmt // /////////////////////////////////////////////////////////////////////////////// class Stmt_FORALLstmt : public a_Stmt { public: #line 101 "../../prop-src/setl-ast.ph" Generators _1; Stmt _2; inline Stmt_FORALLstmt (Generators x_1, Stmt x_2) : a_Stmt(tag_FORALLstmt), _1(x_1), _2(x_2) { } }; /////////////////////////////////////////////////////////////////////////////// // // Class for datatype constructor Stmt::RETURNstmt // /////////////////////////////////////////////////////////////////////////////// class Stmt_RETURNstmt : public a_Stmt { public: #line 102 "../../prop-src/setl-ast.ph" Exp RETURNstmt; inline Stmt_RETURNstmt (Exp x_RETURNstmt) : a_Stmt(tag_RETURNstmt), RETURNstmt(x_RETURNstmt) { } }; /////////////////////////////////////////////////////////////////////////////// // // Datatype constructor functions for Stmt // /////////////////////////////////////////////////////////////////////////////// inline a_Stmt * ASSIGNstmt (Exp x_1, Exp x_2) { return new Stmt_ASSIGNstmt (x_1, x_2); } inline a_Stmt * BLOCKstmt (Defs x_1, Stmts x_2) { return new Stmt_BLOCKstmt (x_1, x_2); } inline a_Stmt * WHILEstmt (Exp x_1, Stmt x_2) { return new Stmt_WHILEstmt (x_1, x_2); } inline a_Stmt * IFstmt (Exp x_1, Stmt x_2, Stmt x_3) { return new Stmt_IFstmt (x_1, x_2, x_3); } inline a_Stmt * MATCHstmt (Decl x_MATCHstmt) { return new Stmt_MATCHstmt (x_MATCHstmt); } inline a_Stmt * REWRITEstmt (Decl x_REWRITEstmt) { return new Stmt_REWRITEstmt (x_REWRITEstmt); } inline a_Stmt * REPLACEMENTstmt (Decl x_REPLACEMENTstmt) { return new Stmt_REPLACEMENTstmt (x_REPLACEMENTstmt); } inline a_Stmt * FORALLstmt (Generators x_1, Stmt x_2) { return new Stmt_FORALLstmt (x_1, x_2); } inline a_Stmt * RETURNstmt (Exp x_RETURNstmt) { return new Stmt_RETURNstmt (x_RETURNstmt); } /////////////////////////////////////////////////////////////////////////////// // // Downcasting functions for Stmt // /////////////////////////////////////////////////////////////////////////////// inline Stmt_ASSIGNstmt * _ASSIGNstmt(const a_Stmt * _x_) { return (Stmt_ASSIGNstmt *)_x_; } inline Stmt_BLOCKstmt * _BLOCKstmt(const a_Stmt * _x_) { return (Stmt_BLOCKstmt *)_x_; } inline Stmt_WHILEstmt * _WHILEstmt(const a_Stmt * _x_) { return (Stmt_WHILEstmt *)_x_; } inline Stmt_IFstmt * _IFstmt(const a_Stmt * _x_) { return (Stmt_IFstmt *)_x_; } inline Stmt_MATCHstmt * _MATCHstmt(const a_Stmt * _x_) { return (Stmt_MATCHstmt *)_x_; } inline Stmt_REWRITEstmt * _REWRITEstmt(const a_Stmt * _x_) { return (Stmt_REWRITEstmt *)_x_; } inline Stmt_REPLACEMENTstmt * _REPLACEMENTstmt(const a_Stmt * _x_) { return (Stmt_REPLACEMENTstmt *)_x_; } inline Stmt_FORALLstmt * _FORALLstmt(const a_Stmt * _x_) { return (Stmt_FORALLstmt *)_x_; } inline Stmt_RETURNstmt * _RETURNstmt(const a_Stmt * _x_) { return (Stmt_RETURNstmt *)_x_; } #line 116 "../../prop-src/setl-ast.ph" #line 116 "../../prop-src/setl-ast.ph" /////////////////////////////////////////////////////////////////////////////// // // Pretty printing routines for definitions, statements and generators // /////////////////////////////////////////////////////////////////////////////// extern std::ostream& operator << (std::ostream&, Def); extern std::ostream& operator << (std::ostream&, Defs); extern std::ostream& operator << (std::ostream&, Sig); extern std::ostream& operator << (std::ostream&, Sigs); extern std::ostream& operator << (std::ostream&, Stmt); extern std::ostream& operator << (std::ostream&, Stmts); extern std::ostream& operator << (std::ostream&, LabSig); extern std::ostream& operator << (std::ostream&, LabSigs); extern std::ostream& operator << (std::ostream&, Generator); extern std::ostream& operator << (std::ostream&, Generators); #endif #line 136 "../../prop-src/setl-ast.ph" /* ------------------------------- Statistics ------------------------------- Merge matching rules = yes Number of DFA nodes merged = 0 Number of ifs generated = 0 Number of switches generated = 0 Number of labels = 0 Number of gotos = 0 Adaptive matching = disabled Fast string matching = disabled Inline downcasts = disabled -------------------------------------------------------------------------- */
[ [ [ 1, 703 ] ] ]
e2927eb7cff9ba43a1fa0e1216be9a5f83e50aef
8d3bc2c1c82dee5806c4503dd0fd32908c78a3a9
/wwscript/src/angelscript/as_builder.cpp
c524ae0a4abfa2359c26b05481c3999d995b4ad1
[]
no_license
ryzom/werewolf2
2645d169381294788bab9a152c4071061063a152
a868205216973cf4d1c7d2a96f65f88360177b69
refs/heads/master
2020-03-22T20:08:32.123283
2010-03-05T21:43:32
2010-03-05T21:43:32
140,575,749
0
0
null
null
null
null
UTF-8
C++
false
false
74,658
cpp
/* AngelCode Scripting Library Copyright (c) 2003-2009 Andreas Jonsson This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. The original version of this library can be located at: http://www.angelcode.com/angelscript/ Andreas Jonsson [email protected] */ // // as_builder.cpp // // This is the class that manages the compilation of the scripts // #include "as_config.h" #include "as_builder.h" #include "as_parser.h" #include "as_compiler.h" #include "as_tokendef.h" #include "as_string_util.h" #include "as_outputbuffer.h" #include "as_texts.h" #include "as_scriptobject.h" BEGIN_AS_NAMESPACE asCBuilder::asCBuilder(asCScriptEngine *engine, asCModule *module) { this->engine = engine; this->module = module; } asCBuilder::~asCBuilder() { asUINT n; // Free all functions for( n = 0; n < functions.GetLength(); n++ ) { if( functions[n] ) { if( functions[n]->node ) { functions[n]->node->Destroy(engine); } asDELETE(functions[n],sFunctionDescription); } functions[n] = 0; } // Free all global variables for( n = 0; n < globVariables.GetLength(); n++ ) { if( globVariables[n] ) { if( globVariables[n]->nextNode ) { globVariables[n]->nextNode->Destroy(engine); } asDELETE(globVariables[n],sGlobalVariableDescription); globVariables[n] = 0; } } // Free all the loaded files for( n = 0; n < scripts.GetLength(); n++ ) { if( scripts[n] ) { asDELETE(scripts[n],asCScriptCode); } scripts[n] = 0; } // Free all class declarations for( n = 0; n < classDeclarations.GetLength(); n++ ) { if( classDeclarations[n] ) { if( classDeclarations[n]->node ) { classDeclarations[n]->node->Destroy(engine); } asDELETE(classDeclarations[n],sClassDeclaration); classDeclarations[n] = 0; } } for( n = 0; n < interfaceDeclarations.GetLength(); n++ ) { if( interfaceDeclarations[n] ) { if( interfaceDeclarations[n]->node ) { interfaceDeclarations[n]->node->Destroy(engine); } asDELETE(interfaceDeclarations[n],sClassDeclaration); interfaceDeclarations[n] = 0; } } for( n = 0; n < namedTypeDeclarations.GetLength(); n++ ) { if( namedTypeDeclarations[n] ) { if( namedTypeDeclarations[n]->node ) { namedTypeDeclarations[n]->node->Destroy(engine); } asDELETE(namedTypeDeclarations[n],sClassDeclaration); namedTypeDeclarations[n] = 0; } } } int asCBuilder::AddCode(const char *name, const char *code, int codeLength, int lineOffset, int sectionIdx, bool makeCopy) { asCScriptCode *script = asNEW(asCScriptCode); script->SetCode(name, code, codeLength, makeCopy); script->lineOffset = lineOffset; script->idx = sectionIdx; scripts.PushLast(script); return 0; } int asCBuilder::Build() { numErrors = 0; numWarnings = 0; preMessage.isSet = false; ParseScripts(); CompileClasses(); CompileGlobalVariables(); CompileFunctions(); if( numErrors > 0 ) return asERROR; return asSUCCESS; } int asCBuilder::BuildString(const char *string, asCContext *ctx) { numErrors = 0; numWarnings = 0; preMessage.isSet = false; // Add the string to the script code asCScriptCode *script = asNEW(asCScriptCode); script->SetCode(TXT_EXECUTESTRING, string, true); script->lineOffset = -1; // Compensate for "void ExecuteString() {\n" scripts.PushLast(script); // Parse the string asCParser parser(this); if( parser.ParseScript(scripts[0]) >= 0 ) { // Find the function asCScriptNode *node = parser.GetScriptNode(); node = node->firstChild; if( node->nodeType == snFunction ) { node->DisconnectParent(); sFunctionDescription *func = asNEW(sFunctionDescription); functions.PushLast(func); func->script = scripts[0]; func->node = node; func->name = ""; } else { // An error occurred asASSERT(false); } } if( numErrors == 0 ) { // Compile the function asCCompiler compiler(engine); asCScriptFunction *execfunc = asNEW(asCScriptFunction)(engine,module); if( compiler.CompileFunction(this, functions[0]->script, functions[0]->node, execfunc) >= 0 ) { execfunc->id = asFUNC_STRING; ctx->SetExecuteStringFunction(execfunc); } else { asDELETE(execfunc,asCScriptFunction); } } if( numErrors > 0 ) return asERROR; return asSUCCESS; } void asCBuilder::ParseScripts() { asCArray<asCParser*> parsers((int)scripts.GetLength()); // Parse all the files as if they were one asUINT n = 0; for( n = 0; n < scripts.GetLength(); n++ ) { asCParser *parser = asNEW(asCParser)(this); parsers.PushLast(parser); // Parse the script file parser->ParseScript(scripts[n]); } if( numErrors == 0 ) { // Find all type declarations for( n = 0; n < scripts.GetLength(); n++ ) { asCScriptNode *node = parsers[n]->GetScriptNode(); // Find structure definitions first node = node->firstChild; while( node ) { asCScriptNode *next = node->next; if( node->nodeType == snClass ) { node->DisconnectParent(); RegisterClass(node, scripts[n]); } else if( node->nodeType == snInterface ) { node->DisconnectParent(); RegisterInterface(node, scripts[n]); } // Handle enumeration else if( node->nodeType == snEnum ) { node->DisconnectParent(); RegisterEnum(node, scripts[n]); } // Handle typedef else if( node->nodeType == snTypedef ) { node->DisconnectParent(); RegisterTypedef(node, scripts[n]); } node = next; } } // Register script methods found in the interfaces for( n = 0; n < interfaceDeclarations.GetLength(); n++ ) { sClassDeclaration *decl = interfaceDeclarations[n]; asCScriptNode *node = decl->node->firstChild->next; while( node ) { asCScriptNode *next = node->next; if( node->nodeType == snFunction ) { node->DisconnectParent(); RegisterScriptFunction(engine->GetNextScriptFunctionId(), node, decl->script, decl->objType, true); } node = next; } } // Now the interfaces have been completely established, now we need to determine if // the same interface has already been registered before, and if so reuse the interface id. module->ResolveInterfaceIds(); // Register script methods found in the structures for( n = 0; n < classDeclarations.GetLength(); n++ ) { sClassDeclaration *decl = classDeclarations[n]; asCScriptNode *node = decl->node->firstChild->next; // Skip list of classes and interfaces while( node && node->nodeType == snIdentifier ) node = node->next; while( node ) { asCScriptNode *next = node->next; if( node->nodeType == snFunction ) { node->DisconnectParent(); RegisterScriptFunction(engine->GetNextScriptFunctionId(), node, decl->script, decl->objType); } node = next; } // Make sure the default factory & constructor exists for classes if( decl->objType->beh.construct == engine->scriptTypeBehaviours.beh.construct ) { AddDefaultConstructor(decl->objType, decl->script); } } // Find other global nodes for( n = 0; n < scripts.GetLength(); n++ ) { // Find other global nodes asCScriptNode *node = parsers[n]->GetScriptNode(); node = node->firstChild; while( node ) { asCScriptNode *next = node->next; node->DisconnectParent(); if( node->nodeType == snFunction ) { RegisterScriptFunction(engine->GetNextScriptFunctionId(), node, scripts[n], 0, false, true); } else if( node->nodeType == snGlobalVar ) { RegisterGlobalVar(node, scripts[n]); } else if( node->nodeType == snImport ) { RegisterImportedFunction(module->GetNextImportedFunctionId(), node, scripts[n]); } else { // Unused script node int r, c; scripts[n]->ConvertPosToRowCol(node->tokenPos, &r, &c); WriteWarning(scripts[n]->name.AddressOf(), TXT_UNUSED_SCRIPT_NODE, r, c); node->Destroy(engine); } node = next; } } } for( n = 0; n < parsers.GetLength(); n++ ) { asDELETE(parsers[n],asCParser); } } void asCBuilder::CompileFunctions() { // Compile each function for( asUINT n = 0; n < functions.GetLength(); n++ ) { if( functions[n] == 0 ) continue; asCCompiler compiler(engine); asCScriptFunction *func = engine->scriptFunctions[functions[n]->funcId]; if( functions[n]->node ) { int r, c; functions[n]->script->ConvertPosToRowCol(functions[n]->node->tokenPos, &r, &c); asCString str = func->GetDeclarationStr(); str.Format(TXT_COMPILING_s, str.AddressOf()); WriteInfo(functions[n]->script->name.AddressOf(), str.AddressOf(), r, c, true); compiler.CompileFunction(this, functions[n]->script, functions[n]->node, func); preMessage.isSet = false; } else { // This is the default constructor, that is generated // automatically if not implemented by the user. asASSERT( functions[n]->name == functions[n]->objType->name ); compiler.CompileDefaultConstructor(this, functions[n]->script, func); } } } int asCBuilder::ParseDataType(const char *datatype, asCDataType *result) { numErrors = 0; numWarnings = 0; preMessage.isSet = false; asCScriptCode source; source.SetCode("", datatype, true); asCParser parser(this); int r = parser.ParseDataType(&source); if( r < 0 ) return asINVALID_TYPE; // Get data type and property name asCScriptNode *dataType = parser.GetScriptNode()->firstChild; *result = CreateDataTypeFromNode(dataType, &source, true); if( numErrors > 0 ) return asINVALID_TYPE; return asSUCCESS; } int asCBuilder::ParseTemplateDecl(const char *decl, asCString *name, asCString *subtypeName) { numErrors = 0; numWarnings = 0; preMessage.isSet = false; asCScriptCode source; source.SetCode("", decl, true); asCParser parser(this); int r = parser.ParseTemplateDecl(&source); if( r < 0 ) return asINVALID_TYPE; // Get the template name and subtype name asCScriptNode *node = parser.GetScriptNode()->firstChild; name->Assign(&decl[node->tokenPos], node->tokenLength); node = node->next; subtypeName->Assign(&decl[node->tokenPos], node->tokenLength); // TODO: template: check for name conflicts if( numErrors > 0 ) return asINVALID_DECLARATION; return asSUCCESS; } int asCBuilder::VerifyProperty(asCDataType *dt, const char *decl, asCString &name, asCDataType &type) { numErrors = 0; numWarnings = 0; preMessage.isSet = false; if( dt ) { // Verify that the object type exist if( dt->GetObjectType() == 0 ) return asINVALID_OBJECT; } // Check property declaration and type asCScriptCode source; source.SetCode(TXT_PROPERTY, decl, true); asCParser parser(this); int r = parser.ParsePropertyDeclaration(&source); if( r < 0 ) return asINVALID_DECLARATION; // Get data type and property name asCScriptNode *dataType = parser.GetScriptNode()->firstChild; asCScriptNode *nameNode = dataType->next; type = CreateDataTypeFromNode(dataType, &source); name.Assign(&decl[nameNode->tokenPos], nameNode->tokenLength); // Verify property name if( dt ) { if( CheckNameConflictMember(*dt, name.AddressOf(), nameNode, &source) < 0 ) return asNAME_TAKEN; } else { if( CheckNameConflict(name.AddressOf(), nameNode, &source) < 0 ) return asNAME_TAKEN; } if( numErrors > 0 ) return asINVALID_DECLARATION; return asSUCCESS; } asCObjectProperty *asCBuilder::GetObjectProperty(asCDataType &obj, const char *prop) { asASSERT(obj.GetObjectType() != 0); // TODO: Only search in config groups to which the module has access // TODO: optimize: Improve linear search asCArray<asCObjectProperty *> &props = obj.GetObjectType()->properties; for( asUINT n = 0; n < props.GetLength(); n++ ) if( props[n]->name == prop ) return props[n]; return 0; } asCGlobalProperty *asCBuilder::GetGlobalProperty(const char *prop, bool *isCompiled, bool *isPureConstant, asQWORD *constantValue) { asUINT n; if( isCompiled ) *isCompiled = true; if( isPureConstant ) *isPureConstant = false; // TODO: optimize: Improve linear search // Check application registered properties asCArray<asCGlobalProperty *> *props = &(engine->registeredGlobalProps); for( n = 0; n < props->GetLength(); ++n ) if( (*props)[n] && (*props)[n]->name == prop ) { if( module ) { // Find the config group for the global property asCConfigGroup *group = engine->FindConfigGroupForGlobalVar((*props)[n]->id); if( !group || group->HasModuleAccess(module->name.AddressOf()) ) return (*props)[n]; } else { // We're not compiling a module right now, so it must be a registered global property return (*props)[n]; } } // TODO: optimize: Improve linear search // Check properties being compiled now asCArray<sGlobalVariableDescription *> *gvars = &globVariables; for( n = 0; n < gvars->GetLength(); ++n ) { if( (*gvars)[n] && (*gvars)[n]->name == prop ) { if( isCompiled ) *isCompiled = (*gvars)[n]->isCompiled; if( isPureConstant ) *isPureConstant = (*gvars)[n]->isPureConstant; if( constantValue ) *constantValue = (*gvars)[n]->constantValue; return (*gvars)[n]->property; } } // TODO: optimize: Improve linear search // Check previously compiled global variables if( module ) { props = &module->scriptGlobals; for( n = 0; n < props->GetLength(); ++n ) if( (*props)[n]->name == prop ) return (*props)[n]; } return 0; } int asCBuilder::ParseFunctionDeclaration(asCObjectType *objType, const char *decl, asCScriptFunction *func, bool isSystemFunction, asCArray<bool> *paramAutoHandles, bool *returnAutoHandle) { numErrors = 0; numWarnings = 0; preMessage.isSet = false; asCScriptCode source; source.SetCode(TXT_SYSTEM_FUNCTION, decl, true); asCParser parser(this); int r = parser.ParseFunctionDefinition(&source); if( r < 0 ) return asINVALID_DECLARATION; asCScriptNode *node = parser.GetScriptNode(); // Find name asCScriptNode *n = node->firstChild->next->next; func->name.Assign(&source.code[n->tokenPos], n->tokenLength); // Initialize a script function object for registration bool autoHandle; // Scoped reference types are allowed to use handle when returned from application functions func->returnType = CreateDataTypeFromNode(node->firstChild, &source, true, objType); func->returnType = ModifyDataTypeFromNode(func->returnType, node->firstChild->next, &source, 0, &autoHandle); if( autoHandle && (!func->returnType.IsObjectHandle() || func->returnType.IsReference()) ) return asINVALID_DECLARATION; if( returnAutoHandle ) *returnAutoHandle = autoHandle; // Reference types cannot be returned by value from system functions if( isSystemFunction && (func->returnType.GetObjectType() && (func->returnType.GetObjectType()->flags & asOBJ_REF)) && !(func->returnType.IsReference() || func->returnType.IsObjectHandle()) ) return asINVALID_DECLARATION; // Count number of parameters int paramCount = 0; n = n->next->firstChild; while( n ) { paramCount++; n = n->next->next; if( n && n->nodeType == snIdentifier ) n = n->next; } // Preallocate memory func->parameterTypes.Allocate(paramCount, false); func->inOutFlags.Allocate(paramCount, false); if( paramAutoHandles ) paramAutoHandles->Allocate(paramCount, false); n = node->firstChild->next->next->next->firstChild; while( n ) { asETypeModifiers inOutFlags; asCDataType type = CreateDataTypeFromNode(n, &source, false, objType); type = ModifyDataTypeFromNode(type, n->next, &source, &inOutFlags, &autoHandle); // Reference types cannot be passed by value to system functions if( isSystemFunction && (type.GetObjectType() && (type.GetObjectType()->flags & asOBJ_REF)) && !(type.IsReference() || type.IsObjectHandle()) ) return asINVALID_DECLARATION; // Store the parameter type func->parameterTypes.PushLast(type); func->inOutFlags.PushLast(inOutFlags); // Don't permit void parameters if( type.GetTokenType() == ttVoid ) return asINVALID_DECLARATION; if( autoHandle && (!type.IsObjectHandle() || type.IsReference()) ) return asINVALID_DECLARATION; if( paramAutoHandles ) paramAutoHandles->PushLast(autoHandle); // Make sure that var type parameters are references if( type.GetTokenType() == ttQuestion && !type.IsReference() ) return asINVALID_DECLARATION; // Move to next parameter n = n->next->next; if( n && n->nodeType == snIdentifier ) n = n->next; } // Set the read-only flag if const is declared after parameter list if( node->lastChild->nodeType == snUndefined && node->lastChild->tokenType == ttConst ) func->isReadOnly = true; else func->isReadOnly = false; if( numErrors > 0 || numWarnings > 0 ) return asINVALID_DECLARATION; return 0; } int asCBuilder::ParseVariableDeclaration(const char *decl, asCObjectProperty *var) { numErrors = 0; numWarnings = 0; preMessage.isSet = false; asCScriptCode source; source.SetCode(TXT_VARIABLE_DECL, decl, true); asCParser parser(this); int r = parser.ParsePropertyDeclaration(&source); if( r < 0 ) return asINVALID_DECLARATION; asCScriptNode *node = parser.GetScriptNode(); // Find name asCScriptNode *n = node->firstChild->next; var->name.Assign(&source.code[n->tokenPos], n->tokenLength); // Initialize a script variable object for registration var->type = CreateDataTypeFromNode(node->firstChild, &source); if( numErrors > 0 || numWarnings > 0 ) return asINVALID_DECLARATION; return 0; } int asCBuilder::CheckNameConflictMember(asCDataType &dt, const char *name, asCScriptNode *node, asCScriptCode *code) { // It's not necessary to check against object types // Check against other members asCObjectType *t = dt.GetObjectType(); // TODO: optimize: Improve linear search asCArray<asCObjectProperty *> &props = t->properties; for( asUINT n = 0; n < props.GetLength(); n++ ) { if( props[n]->name == name ) { if( code ) { int r, c; code->ConvertPosToRowCol(node->tokenPos, &r, &c); asCString str; str.Format(TXT_NAME_CONFLICT_s_OBJ_PROPERTY, name); WriteError(code->name.AddressOf(), str.AddressOf(), r, c); } return -1; } } // TODO: Property names must be checked against method names return 0; } int asCBuilder::CheckNameConflict(const char *name, asCScriptNode *node, asCScriptCode *code) { // TODO: Must verify object types in all config groups, whether the module has access or not // Check against object types if( engine->GetObjectType(name) != 0 ) { if( code ) { int r, c; code->ConvertPosToRowCol(node->tokenPos, &r, &c); asCString str; str.Format(TXT_NAME_CONFLICT_s_EXTENDED_TYPE, name); WriteError(code->name.AddressOf(), str.AddressOf(), r, c); } return -1; } // TODO: Must verify global properties in all config groups, whether the module has access or not // Check against global properties asCGlobalProperty *prop = GetGlobalProperty(name, 0, 0, 0); if( prop ) { if( code ) { int r, c; code->ConvertPosToRowCol(node->tokenPos, &r, &c); asCString str; str.Format(TXT_NAME_CONFLICT_s_GLOBAL_PROPERTY, name); WriteError(code->name.AddressOf(), str.AddressOf(), r, c); } return -1; } // TODO: Property names must be checked against function names // Check against class types asUINT n; for( n = 0; n < classDeclarations.GetLength(); n++ ) { if( classDeclarations[n]->name == name ) { if( code ) { int r, c; code->ConvertPosToRowCol(node->tokenPos, &r, &c); asCString str; str.Format(TXT_NAME_CONFLICT_s_STRUCT, name); WriteError(code->name.AddressOf(), str.AddressOf(), r, c); } return -1; } } // Check against named types for( n = 0; n < namedTypeDeclarations.GetLength(); n++ ) { if( namedTypeDeclarations[n]->name == name ) { if( code ) { int r, c; code->ConvertPosToRowCol(node->tokenPos, &r, &c); asCString str; // TODO: Need a TXT constant str.Format("Name conflict. '%s' is a named type (FIXME!).", name); WriteError(code->name.AddressOf(), str.AddressOf(), r, c); } return -1; } } return 0; } int asCBuilder::RegisterGlobalVar(asCScriptNode *node, asCScriptCode *file) { // What data type is it? asCDataType type = CreateDataTypeFromNode(node->firstChild, file); if( !type.CanBeInstanciated() ) { asCString str; // TODO: Change to "'type' cannot be declared as variable" str.Format(TXT_DATA_TYPE_CANT_BE_s, type.Format().AddressOf()); int r, c; file->ConvertPosToRowCol(node->tokenPos, &r, &c); WriteError(file->name.AddressOf(), str.AddressOf(), r, c); } asCScriptNode *n = node->firstChild->next; while( n ) { // Verify that the name isn't taken asCString name(&file->code[n->tokenPos], n->tokenLength); CheckNameConflict(name.AddressOf(), n, file); // Register the global variable sGlobalVariableDescription *gvar = asNEW(sGlobalVariableDescription); globVariables.PushLast(gvar); gvar->script = file; gvar->name = name; gvar->isCompiled = false; gvar->datatype = type; gvar->isEnumValue = false; // TODO: Give error message if wrong asASSERT(!gvar->datatype.IsReference()); gvar->idNode = n; gvar->nextNode = 0; if( n->next && (n->next->nodeType == snAssignment || n->next->nodeType == snArgList || n->next->nodeType == snInitList ) ) { gvar->nextNode = n->next; n->next->DisconnectParent(); } gvar->property = module->AllocateGlobalProperty(name.AddressOf(), gvar->datatype); gvar->index = gvar->property->id; n = n->next; } node->Destroy(engine); return 0; } int asCBuilder::RegisterClass(asCScriptNode *node, asCScriptCode *file) { asCScriptNode *n = node->firstChild; asCString name(&file->code[n->tokenPos], n->tokenLength); int r, c; file->ConvertPosToRowCol(n->tokenPos, &r, &c); CheckNameConflict(name.AddressOf(), n, file); sClassDeclaration *decl = asNEW(sClassDeclaration); classDeclarations.PushLast(decl); decl->name = name; decl->script = file; decl->validState = 0; decl->node = node; asCObjectType *st = asNEW(asCObjectType)(engine); st->flags = asOBJ_REF | asOBJ_SCRIPT_OBJECT; if( node->tokenType == ttHandle ) st->flags |= asOBJ_IMPLICIT_HANDLE; st->size = sizeof(asCScriptObject); st->name = name; module->classTypes.PushLast(st); engine->classTypes.PushLast(st); st->AddRef(); decl->objType = st; // Use the default script class behaviours st->beh = engine->scriptTypeBehaviours.beh; return 0; } int asCBuilder::RegisterInterface(asCScriptNode *node, asCScriptCode *file) { asCScriptNode *n = node->firstChild; asCString name(&file->code[n->tokenPos], n->tokenLength); int r, c; file->ConvertPosToRowCol(n->tokenPos, &r, &c); CheckNameConflict(name.AddressOf(), n, file); sClassDeclaration *decl = asNEW(sClassDeclaration); interfaceDeclarations.PushLast(decl); decl->name = name; decl->script = file; decl->validState = 0; decl->node = node; // Register the object type for the interface asCObjectType *st = asNEW(asCObjectType)(engine); st->flags = asOBJ_REF | asOBJ_SCRIPT_OBJECT; st->size = 0; // Cannot be instanciated st->name = name; module->classTypes.PushLast(st); engine->classTypes.PushLast(st); st->AddRef(); decl->objType = st; // Use the default script class behaviours st->beh.construct = 0; st->beh.addref = engine->scriptTypeBehaviours.beh.addref; st->beh.release = engine->scriptTypeBehaviours.beh.release; st->beh.copy = 0; return 0; } void asCBuilder::CompileGlobalVariables() { asUINT n; bool compileSucceeded = true; asCByteCode finalInit(engine); // Store state of compilation (errors, warning, output) int currNumErrors = numErrors; int currNumWarnings = numWarnings; // Backup the original message stream bool msgCallback = engine->msgCallback; asSSystemFunctionInterface msgCallbackFunc = engine->msgCallbackFunc; void *msgCallbackObj = engine->msgCallbackObj; // Set the new temporary message stream asCOutputBuffer outBuffer; engine->SetMessageCallback(asMETHOD(asCOutputBuffer, Callback), &outBuffer, asCALL_THISCALL); asCOutputBuffer finalOutput; // We first try to compile all the primitive global variables, and only after that // compile the non-primitive global variables. This permits the constructors // for the complex types to use the already initialized variables of primitive // type. Note, we currently don't know which global variables are used in the // constructors, so we cannot guarantee that variables of complex types are // initialized in the correct order, so we won't reorder those. bool compilingPrimitives = true; // Compile each global variable while( compileSucceeded ) { compileSucceeded = false; int accumErrors = 0; int accumWarnings = 0; // Restore state of compilation finalOutput.Clear(); for( asUINT n = 0; n < globVariables.GetLength(); n++ ) { asCByteCode init(engine); numWarnings = 0; numErrors = 0; outBuffer.Clear(); sGlobalVariableDescription *gvar = globVariables[n]; if( gvar->isCompiled ) continue; // Skip this for now if we're not compiling complex types yet if( compilingPrimitives && !gvar->datatype.IsPrimitive() ) continue; if( gvar->nextNode ) { int r, c; gvar->script->ConvertPosToRowCol(gvar->nextNode->tokenPos, &r, &c); asCString str = gvar->datatype.Format(); str += " " + gvar->name; str.Format(TXT_COMPILING_s, str.AddressOf()); WriteInfo(gvar->script->name.AddressOf(), str.AddressOf(), r, c, true); } if( gvar->isEnumValue ) { int r; if( gvar->nextNode ) { asCCompiler comp(engine); // Temporarily switch the type of the variable to int so it can be compiled properly asCDataType saveType; saveType = gvar->datatype; gvar->datatype = asCDataType::CreatePrimitive(ttInt, true); r = comp.CompileGlobalVariable(this, gvar->script, gvar->nextNode, gvar); gvar->datatype = saveType; } else { r = 0; // When there is no assignment the value is the last + 1 int enumVal = 0; if( n > 0 ) { sGlobalVariableDescription *gvar2 = globVariables[n-1]; if( gvar2->datatype == gvar->datatype ) { // The integer value is stored in the lower bytes enumVal = (*(int*)&gvar2->constantValue) + 1; if( !gvar2->isCompiled ) { // TODO: Need to get the correct script position int row, col; gvar->script->ConvertPosToRowCol(0, &row, &col); asCString str = gvar->datatype.Format(); str += " " + gvar->name; str.Format(TXT_COMPILING_s, str.AddressOf()); WriteInfo(gvar->script->name.AddressOf(), str.AddressOf(), row, col, true); str.Format(TXT_UNINITIALIZED_GLOBAL_VAR_s, gvar2->name.AddressOf()); WriteError(gvar->script->name.AddressOf(), str.AddressOf(), row, col); r = -1; } } } // The integer value is stored in the lower bytes *(int*)&gvar->constantValue = enumVal; } if( r >= 0 ) { // Set the value as compiled gvar->isCompiled = true; compileSucceeded = true; } } else { // Compile the global variable asCCompiler comp(engine); int r = comp.CompileGlobalVariable(this, gvar->script, gvar->nextNode, gvar); if( r >= 0 ) { // Compilation succeeded gvar->isCompiled = true; compileSucceeded = true; init.AddCode(&comp.byteCode); } } if( gvar->isCompiled ) { // Add warnings for this constant to the total build if( numWarnings ) { currNumWarnings += numWarnings; if( msgCallback ) outBuffer.SendToCallback(engine, &msgCallbackFunc, msgCallbackObj); } // Add compiled byte code to the final init and exit functions finalInit.AddCode(&init); } else { // Add output to final output finalOutput.Append(outBuffer); accumErrors += numErrors; accumWarnings += numWarnings; } preMessage.isSet = false; } if( !compileSucceeded ) { if( compilingPrimitives ) { // No more primitives could be compiled, so // switch to compiling the complex variables compilingPrimitives = false; compileSucceeded = true; } else { // No more variables can be compiled // Add errors and warnings to total build currNumWarnings += accumWarnings; currNumErrors += accumErrors; if( msgCallback ) finalOutput.SendToCallback(engine, &msgCallbackFunc, msgCallbackObj); } } } // Restore states engine->msgCallback = msgCallback; engine->msgCallbackFunc = msgCallbackFunc; engine->msgCallbackObj = msgCallbackObj; numWarnings = currNumWarnings; numErrors = currNumErrors; // Register init code and clean up code finalInit.Ret(0); finalInit.Finalize(); int id = engine->GetNextScriptFunctionId(); asCScriptFunction *init = asNEW(asCScriptFunction)(engine,module); init->id = id; module->initFunction = init; engine->SetScriptFunction(init); init->byteCode.SetLength(finalInit.GetSize()); finalInit.Output(init->byteCode.AddressOf()); init->AddReferences(); init->stackNeeded = finalInit.largestStackUsed; // Convert all variables compiled for the enums to true enum values for( n = 0; n < globVariables.GetLength(); n++ ) { asCObjectType *objectType; sGlobalVariableDescription *gvar = globVariables[n]; if( !gvar->isEnumValue ) continue; objectType = gvar->datatype.GetObjectType(); asASSERT(NULL != objectType); asSEnumValue *e = asNEW(asSEnumValue); e->name = gvar->name; e->value = *(int*)&gvar->constantValue; objectType->enumValues.PushLast(e); // Destroy the gvar property if( gvar->nextNode ) gvar->nextNode->Destroy(engine); if( gvar->property ) asDELETE(gvar->property, asCGlobalProperty); asDELETE(gvar, sGlobalVariableDescription); globVariables[n] = 0; } #ifdef AS_DEBUG // DEBUG: output byte code finalInit.DebugOutput("[email protected]", module, engine); #endif } void asCBuilder::CompileClasses() { asUINT n; asCArray<sClassDeclaration*> toValidate((int)classDeclarations.GetLength()); // Determine class inheritances and interfaces for( n = 0; n < classDeclarations.GetLength(); n++ ) { sClassDeclaration *decl = classDeclarations[n]; asCScriptCode *file = decl->script; // Find the base class that this class inherits from bool multipleInheritance = false; asCScriptNode *node = decl->node->firstChild->next; while( node && node->nodeType == snIdentifier ) { // Get the interface name from the node asCString name(&file->code[node->tokenPos], node->tokenLength); // Find the object type for the interface asCObjectType *objType = GetObjectType(name.AddressOf()); if( objType == 0 ) { int r, c; file->ConvertPosToRowCol(node->tokenPos, &r, &c); asCString str; str.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE, name.AddressOf()); WriteError(file->name.AddressOf(), str.AddressOf(), r, c); } else if( !(objType->flags & asOBJ_SCRIPT_OBJECT) ) { int r, c; file->ConvertPosToRowCol(node->tokenPos, &r, &c); asCString str; str.Format(TXT_CANNOT_INHERIT_FROM_s, objType->name.AddressOf()); WriteError(file->name.AddressOf(), str.AddressOf(), r, c); } else if( objType->size != 0 ) { // The class inherits from another script class if( decl->objType->derivedFrom != 0 ) { if( !multipleInheritance ) { int r, c; file->ConvertPosToRowCol(node->tokenPos, &r, &c); WriteError(file->name.AddressOf(), TXT_CANNOT_INHERIT_FROM_MULTIPLE_CLASSES, r, c); multipleInheritance = true; } } else { // Make sure none of the base classes inherit from this one asCObjectType *base = objType; bool error = false; while( base != 0 ) { if( base == decl->objType ) { int r, c; file->ConvertPosToRowCol(node->tokenPos, &r, &c); WriteError(file->name.AddressOf(), TXT_CANNOT_INHERIT_FROM_SELF, r, c); error = true; break; } base = base->derivedFrom; } if( !error ) { decl->objType->derivedFrom = objType; objType->AddRef(); } } } else { // The class implements an interface if( decl->objType->Implements(objType) ) { int r, c; file->ConvertPosToRowCol(node->tokenPos, &r, &c); asCString msg; msg.Format(TXT_INTERFACE_s_ALREADY_IMPLEMENTED, objType->GetName()); WriteWarning(file->name.AddressOf(), msg.AddressOf(), r, c); } else { decl->objType->interfaces.PushLast(objType); // Make sure all the methods of the interface are implemented for( asUINT i = 0; i < objType->methods.GetLength(); i++ ) { if( !DoesMethodExist(decl->objType, objType->methods[i]) ) { int r, c; file->ConvertPosToRowCol(decl->node->tokenPos, &r, &c); asCString str; str.Format(TXT_MISSING_IMPLEMENTATION_OF_s, engine->GetFunctionDeclaration(objType->methods[i]).AddressOf()); WriteError(file->name.AddressOf(), str.AddressOf(), r, c); } } } } node = node->next; } } // Order class declarations so that base classes are compiled before derived classes. // This will allow the derived classes to copy properties and methods in the next step. for( n = 0; n < classDeclarations.GetLength(); n++ ) { sClassDeclaration *decl = classDeclarations[n]; asCObjectType *derived = decl->objType; asCObjectType *base = derived->derivedFrom; if( base == 0 ) continue; // If the base class is found after the derived class, then move the derived class to the end of the list for( asUINT m = n+1; m < classDeclarations.GetLength(); m++ ) { sClassDeclaration *declBase = classDeclarations[m]; if( base == declBase->objType ) { classDeclarations.RemoveIndex(n); classDeclarations.PushLast(decl); // Decrease index so that we don't skip an entry n--; break; } } } // Go through each of the classes and register the object type descriptions for( n = 0; n < classDeclarations.GetLength(); n++ ) { sClassDeclaration *decl = classDeclarations[n]; // Add all properties and methods from the base class if( decl->objType->derivedFrom ) { asCObjectType *baseType = decl->objType->derivedFrom; // The derived class inherits all interfaces from the base class for( unsigned int n = 0; n < baseType->interfaces.GetLength(); n++ ) { if( !decl->objType->Implements(baseType->interfaces[n]) ) { decl->objType->interfaces.PushLast(baseType->interfaces[n]); } else { // Warn if derived class already implements the interface int r, c; decl->script->ConvertPosToRowCol(decl->node->tokenPos, &r, &c); asCString msg; msg.Format(TXT_INTERFACE_s_ALREADY_IMPLEMENTED, baseType->interfaces[n]->GetName()); WriteWarning(decl->script->name.AddressOf(), msg.AddressOf(), r, c); } } // TODO: Need to check for name conflict with new class methods // Copy properties from base class to derived class for( asUINT p = 0; p < baseType->properties.GetLength(); p++ ) { asCObjectProperty *prop = AddPropertyToClass(decl, baseType->properties[p]->name, baseType->properties[p]->type); // The properties must maintain the same offset asASSERT(prop->byteOffset == baseType->properties[p]->byteOffset); UNUSED_VAR(prop); } // Copy methods from base class to derived class for( asUINT m = 0; m < baseType->methods.GetLength(); m++ ) { // If the derived class implements the same method, then don't add the base class' method asCScriptFunction *baseFunc = GetFunctionDescription(baseType->methods[m]); asCScriptFunction *derivedFunc = 0; bool found = false; for( asUINT d = 0; d < decl->objType->methods.GetLength(); d++ ) { derivedFunc = GetFunctionDescription(decl->objType->methods[d]); if( derivedFunc->IsSignatureEqual(baseFunc) ) { decl->objType->methods.RemoveIndex(d); found = true; break; } } if( !found ) { // Push the base class function on the virtual function table decl->objType->virtualFunctionTable.PushLast(baseType->virtualFunctionTable[m]); } else { // Push the derived class function on the virtual function table decl->objType->virtualFunctionTable.PushLast(derivedFunc); } decl->objType->methods.PushLast(baseType->methods[m]); } } // Move this class' methods into the virtual function table for( asUINT m = 0; m < decl->objType->methods.GetLength(); m++ ) { asCScriptFunction *func = GetFunctionDescription(decl->objType->methods[m]); if( func->funcType != asFUNC_VIRTUAL ) { decl->objType->virtualFunctionTable.PushLast(GetFunctionDescription(decl->objType->methods[m])); // Substitute the function description in the method list for a virtual method // Make sure the methods are in the same order as the virtual function table decl->objType->methods.RemoveIndex(m); decl->objType->methods.PushLast(CreateVirtualFunction(func, (int)decl->objType->virtualFunctionTable.GetLength() - 1)); m--; } } // Enumerate each of the declared properties asCScriptNode *node = decl->node->firstChild->next; // Skip list of classes and interfaces while( node && node->nodeType == snIdentifier ) node = node->next; while( node ) { if( node->nodeType == snDeclaration ) { asCScriptCode *file = decl->script; asCDataType dt = CreateDataTypeFromNode(node->firstChild, file); asCString name(&file->code[node->lastChild->tokenPos], node->lastChild->tokenLength); if( dt.IsReadOnly() ) { int r, c; file->ConvertPosToRowCol(node->tokenPos, &r, &c); WriteError(file->name.AddressOf(), TXT_PROPERTY_CANT_BE_CONST, r, c); } asCDataType st; st.SetObjectType(decl->objType); CheckNameConflictMember(st, name.AddressOf(), node->lastChild, file); AddPropertyToClass(decl, name, dt, file, node); } else asASSERT(false); node = node->next; } toValidate.PushLast(decl); } // Verify that the declared structures are valid, e.g. that the structure // doesn't contain a member of its own type directly or indirectly while( toValidate.GetLength() > 0 ) { asUINT numClasses = (asUINT)toValidate.GetLength(); asCArray<sClassDeclaration*> toValidateNext((int)toValidate.GetLength()); while( toValidate.GetLength() > 0 ) { sClassDeclaration *decl = toValidate[toValidate.GetLength()-1]; int validState = 1; for( asUINT n = 0; n < decl->objType->properties.GetLength(); n++ ) { // A valid structure is one that uses only primitives or other valid objects asCObjectProperty *prop = decl->objType->properties[n]; asCDataType dt = prop->type; if( dt.IsTemplate() ) { asCDataType sub = dt; while( sub.IsTemplate() && !sub.IsObjectHandle() ) sub = sub.GetSubType(); dt = sub; } if( dt.IsObject() && !dt.IsObjectHandle() ) { // Find the class declaration sClassDeclaration *pdecl = 0; for( asUINT p = 0; p < classDeclarations.GetLength(); p++ ) { if( classDeclarations[p]->objType == dt.GetObjectType() ) { pdecl = classDeclarations[p]; break; } } if( pdecl ) { if( pdecl->objType == decl->objType ) { int r, c; decl->script->ConvertPosToRowCol(decl->node->tokenPos, &r, &c); WriteError(decl->script->name.AddressOf(), TXT_ILLEGAL_MEMBER_TYPE, r, c); validState = 2; break; } else if( pdecl->validState != 1 ) { validState = pdecl->validState; break; } } } } if( validState == 1 ) { decl->validState = 1; toValidate.PopLast(); } else if( validState == 2 ) { decl->validState = 2; toValidate.PopLast(); } else { toValidateNext.PushLast(toValidate.PopLast()); } } toValidate = toValidateNext; toValidateNext.SetLength(0); if( numClasses == toValidate.GetLength() ) { int r, c; toValidate[0]->script->ConvertPosToRowCol(toValidate[0]->node->tokenPos, &r, &c); WriteError(toValidate[0]->script->name.AddressOf(), TXT_ILLEGAL_MEMBER_TYPE, r, c); break; } } if( numErrors > 0 ) return; // TODO: The declarations form a graph, all circles in // the graph must be flagged as potential circles // Verify potential circular references for( n = 0; n < classDeclarations.GetLength(); n++ ) { sClassDeclaration *decl = classDeclarations[n]; asCObjectType *ot = decl->objType; // Is there some path in which this structure is involved in circular references? for( asUINT p = 0; p < ot->properties.GetLength(); p++ ) { asCDataType dt = ot->properties[p]->type; if( dt.IsObject() ) { if( dt.IsObjectHandle() ) { // TODO: Can this handle really generate a circular reference? // Only if the handle is of a type that can reference this type, either directly or indirectly ot->flags |= asOBJ_GC; } else if( dt.GetObjectType()->flags & asOBJ_GC ) { // TODO: Just because the member type is a potential circle doesn't mean that this one is // Only if the object is of a type that can reference this type, either directly or indirectly ot->flags |= asOBJ_GC; } if( dt.IsArrayType() ) { asCDataType sub = dt.GetSubType(); while( sub.IsObject() ) { if( sub.IsObjectHandle() || (sub.GetObjectType()->flags & asOBJ_GC) ) { decl->objType->flags |= asOBJ_GC; // Make sure the array object is also marked as potential circle sub = dt; while( sub.IsTemplate() ) { sub.GetObjectType()->flags |= asOBJ_GC; sub = sub.GetSubType(); } break; } if( sub.IsTemplate() ) sub = sub.GetSubType(); else break; } } } } } } int asCBuilder::CreateVirtualFunction(asCScriptFunction *func, int idx) { asCScriptFunction *vf = asNEW(asCScriptFunction)(engine, module); vf->funcType = asFUNC_VIRTUAL; vf->name = func->name; vf->returnType = func->returnType; vf->parameterTypes = func->parameterTypes; vf->inOutFlags = func->inOutFlags; vf->id = engine->GetNextScriptFunctionId(); vf->scriptSectionIdx = func->scriptSectionIdx; vf->isReadOnly = func->isReadOnly; vf->objectType = func->objectType; vf->signatureId = func->signatureId; vf->vfTableIdx = idx; module->AddScriptFunction(vf); // Add a dummy to the builder so that it doesn't mix up function ids functions.PushLast(0); return vf->id; } asCObjectProperty *asCBuilder::AddPropertyToClass(sClassDeclaration *decl, const asCString &name, const asCDataType &dt, asCScriptCode *file, asCScriptNode *node) { // Store the properties in the object type descriptor asCObjectProperty *prop = asNEW(asCObjectProperty); prop->name = name; prop->type = dt; int propSize; if( dt.IsObject() ) { propSize = dt.GetSizeOnStackDWords()*4; if( !dt.IsObjectHandle() ) { if( !dt.CanBeInstanciated() ) { asASSERT( file && node ); int r, c; file->ConvertPosToRowCol(node->tokenPos, &r, &c); asCString str; str.Format(TXT_DATA_TYPE_CANT_BE_s, dt.Format().AddressOf()); WriteError(file->name.AddressOf(), str.AddressOf(), r, c); } prop->type.MakeReference(true); } } else { propSize = dt.GetSizeInMemoryBytes(); if( propSize == 0 && file && node ) { int r, c; file->ConvertPosToRowCol(node->tokenPos, &r, &c); asCString str; str.Format(TXT_DATA_TYPE_CANT_BE_s, dt.Format().AddressOf()); WriteError(file->name.AddressOf(), str.AddressOf(), r, c); } } // Add extra bytes so that the property will be properly aligned if( propSize == 2 && (decl->objType->size & 1) ) decl->objType->size += 1; if( propSize > 2 && (decl->objType->size & 3) ) decl->objType->size += 4 - (decl->objType->size & 3); prop->byteOffset = decl->objType->size; decl->objType->size += propSize; decl->objType->properties.PushLast(prop); // Make sure the struct holds a reference to the config group where the object is registered asCConfigGroup *group = engine->FindConfigGroupForObjectType(prop->type.GetObjectType()); if( group != 0 ) group->AddRef(); return prop; } bool asCBuilder::DoesMethodExist(asCObjectType *objType, int methodId) { asCScriptFunction *method = GetFunctionDescription(methodId); for( asUINT n = 0; n < objType->methods.GetLength(); n++ ) { asCScriptFunction *m = GetFunctionDescription(objType->methods[n]); if( m->name != method->name ) continue; if( m->returnType != method->returnType ) continue; if( m->isReadOnly != method->isReadOnly ) continue; if( m->parameterTypes != method->parameterTypes ) continue; if( m->inOutFlags != method->inOutFlags ) continue; return true; } return false; } void asCBuilder::AddDefaultConstructor(asCObjectType *objType, asCScriptCode *file) { int funcId = engine->GetNextScriptFunctionId(); asCDataType returnType = asCDataType::CreatePrimitive(ttVoid, false); asCArray<asCDataType> parameterTypes; asCArray<asETypeModifiers> inOutFlags; // Add the script function module->AddScriptFunction(file->idx, funcId, objType->name.AddressOf(), returnType, parameterTypes.AddressOf(), inOutFlags.AddressOf(), (asUINT)parameterTypes.GetLength(), false, objType); // Set it as default constructor objType->beh.construct = funcId; objType->beh.constructors[0] = funcId; // The bytecode for the default constructor will be generated // only after the potential inheritance has been established sFunctionDescription *func = asNEW(sFunctionDescription); functions.PushLast(func); func->script = file; func->node = 0; func->name = objType->name; func->objType = objType; func->funcId = funcId; // Add a default factory as well funcId = engine->GetNextScriptFunctionId(); objType->beh.factory = funcId; objType->beh.factories[0] = funcId; returnType = asCDataType::CreateObjectHandle(objType, false); module->AddScriptFunction(file->idx, funcId, objType->name.AddressOf(), returnType, parameterTypes.AddressOf(), inOutFlags.AddressOf(), (asUINT)parameterTypes.GetLength(), false); functions.PushLast(0); asCCompiler compiler(engine); compiler.CompileFactory(this, file, engine->scriptFunctions[funcId]); } int asCBuilder::RegisterEnum(asCScriptNode *node, asCScriptCode *file) { // Grab the name of the enumeration asCScriptNode *tmp = node->firstChild; asASSERT(snDataType == tmp->nodeType); asCString name; asASSERT(snIdentifier == tmp->firstChild->nodeType); name.Assign(&file->code[tmp->firstChild->tokenPos], tmp->firstChild->tokenLength); // Check the name and add the enum int r = CheckNameConflict(name.AddressOf(), tmp->firstChild, file); if( asSUCCESS == r ) { asCObjectType *st; asCDataType dataType; st = asNEW(asCObjectType)(engine); dataType.CreatePrimitive(ttInt, false); st->flags = asOBJ_ENUM; st->size = dataType.GetSizeInMemoryBytes(); st->name = name; module->enumTypes.PushLast(st); st->AddRef(); engine->classTypes.PushLast(st); // Store the location of this declaration for reference in name collisions sClassDeclaration *decl = asNEW(sClassDeclaration); decl->name = name; decl->script = file; decl->validState = 0; decl->node = NULL; decl->objType = st; namedTypeDeclarations.PushLast(decl); asCDataType type = CreateDataTypeFromNode(tmp, file); asASSERT(!type.IsReference()); tmp = tmp->next; while( tmp ) { asASSERT(snIdentifier == tmp->nodeType); asCString name(&file->code[tmp->tokenPos], tmp->tokenLength); // TODO: Should only have to check for conflicts within the enum type // Check for name conflict errors r = CheckNameConflict(name.AddressOf(), tmp, file); if(asSUCCESS != r) { continue; } // check for assignment asCScriptNode *asnNode = tmp->next; if( asnNode && snAssignment == asnNode->nodeType ) asnNode->DisconnectParent(); else asnNode = 0; // Create the global variable description so the enum value can be evaluated sGlobalVariableDescription *gvar = asNEW(sGlobalVariableDescription); globVariables.PushLast(gvar); gvar->script = file; gvar->idNode = 0; gvar->nextNode = asnNode; gvar->name = name; gvar->datatype = type; // No need to allocate space on the global memory stack since the values are stored in the asCObjectType gvar->index = 0; gvar->isCompiled = false; gvar->isPureConstant = true; gvar->isEnumValue = true; gvar->constantValue = 0xdeadbeef; // Allocate dummy property so we can compile the value. // This will be removed later on so we don't add it to the engine. gvar->property = asNEW(asCGlobalProperty); gvar->property->name = name; gvar->property->type = gvar->datatype; gvar->property->id = 0; tmp = tmp->next; } } node->Destroy(engine); return r; } int asCBuilder::RegisterTypedef(asCScriptNode *node, asCScriptCode *file) { // Get the native data type asCScriptNode *tmp = node->firstChild; asASSERT(NULL != tmp && snDataType == tmp->nodeType); asCDataType dataType; dataType.CreatePrimitive(tmp->tokenType, false); dataType.SetTokenType(tmp->tokenType); tmp = tmp->next; // Grab the name of the typedef asASSERT(NULL != tmp && NULL == tmp->next); asCString name; name.Assign(&file->code[tmp->tokenPos], tmp->tokenLength); // If the name is not already in use add it int r = CheckNameConflict(name.AddressOf(), tmp, file); if( asSUCCESS == r ) { // Create the new type asCObjectType *st = asNEW(asCObjectType)(engine); st->flags = asOBJ_TYPEDEF; st->size = dataType.GetSizeInMemoryBytes(); st->name = name; st->templateSubType = dataType; st->AddRef(); module->typeDefs.PushLast(st); engine->classTypes.PushLast(st); // Store the location of this declaration for reference in name collisions sClassDeclaration *decl = asNEW(sClassDeclaration); decl->name = name; decl->script = file; decl->validState = 0; decl->node = NULL; decl->objType = st; namedTypeDeclarations.PushLast(decl); } node->Destroy(engine); if( r < 0 ) { engine->ConfigError(r); } return 0; } int asCBuilder::RegisterScriptFunction(int funcID, asCScriptNode *node, asCScriptCode *file, asCObjectType *objType, bool isInterface, bool isGlobalFunction) { // Find name bool isConstructor = false; bool isDestructor = false; asCScriptNode *n = 0; if( node->firstChild->nodeType == snDataType ) n = node->firstChild->next->next; else { // If the first node is a ~ token, then we know it is a destructor if( node->firstChild->tokenType == ttBitNot ) { n = node->firstChild->next; isDestructor = true; } else { n = node->firstChild; isConstructor = true; } } // Check for name conflicts asCString name(&file->code[n->tokenPos], n->tokenLength); if( !isConstructor && !isDestructor ) { asCDataType dt = asCDataType::CreateObject(objType, false); if( objType ) CheckNameConflictMember(dt, name.AddressOf(), n, file); else CheckNameConflict(name.AddressOf(), n, file); } else { // Verify that the name of the constructor/destructor is the same as the class if( name != objType->name ) { int r, c; file->ConvertPosToRowCol(n->tokenPos, &r, &c); WriteError(file->name.AddressOf(), TXT_CONSTRUCTOR_NAME_ERROR, r, c); } if( isDestructor ) name = "~" + name; } if( !isInterface ) { sFunctionDescription *func = asNEW(sFunctionDescription); functions.PushLast(func); func->script = file; func->node = node; func->name = name; func->objType = objType; func->funcId = funcID; } // Initialize a script function object for registration asCDataType returnType = asCDataType::CreatePrimitive(ttVoid, false); if( !isConstructor && !isDestructor ) { returnType = CreateDataTypeFromNode(node->firstChild, file); returnType = ModifyDataTypeFromNode(returnType, node->firstChild->next, file, 0, 0); } // Is this a const method? bool isConstMethod = false; if( objType && n->next->next && n->next->next->tokenType == ttConst ) isConstMethod = true; // Count the number of parameters int count = 0; asCScriptNode *c = n->next->firstChild; while( c ) { count++; c = c->next->next; if( c && c->nodeType == snIdentifier ) c = c->next; } // Destructors may not have any parameters if( isDestructor && count > 0 ) { int r, c; file->ConvertPosToRowCol(node->tokenPos, &r, &c); WriteError(file->name.AddressOf(), TXT_DESTRUCTOR_MAY_NOT_HAVE_PARM, r, c); } asCArray<asCDataType> parameterTypes(count); asCArray<asETypeModifiers> inOutFlags(count); n = n->next->firstChild; while( n ) { asETypeModifiers inOutFlag; asCDataType type = CreateDataTypeFromNode(n, file); type = ModifyDataTypeFromNode(type, n->next, file, &inOutFlag, 0); // Store the parameter type parameterTypes.PushLast(type); inOutFlags.PushLast(inOutFlag); // Move to next parameter n = n->next->next; if( n && n->nodeType == snIdentifier ) n = n->next; } // TODO: Much of this can probably be reduced by using the IsSignatureEqual method // Check that the same function hasn't been registered already asCArray<int> funcs; GetFunctionDescriptions(name.AddressOf(), funcs); if( funcs.GetLength() ) { for( asUINT n = 0; n < funcs.GetLength(); ++n ) { asCScriptFunction *func = GetFunctionDescription(funcs[n]); if( parameterTypes.GetLength() == func->parameterTypes.GetLength() ) { bool match = true; if( func->objectType != objType ) { match = false; break; } for( asUINT p = 0; p < parameterTypes.GetLength(); ++p ) { if( parameterTypes[p] != func->parameterTypes[p] ) { match = false; break; } } if( match ) { int r, c; file->ConvertPosToRowCol(node->tokenPos, &r, &c); WriteError(file->name.AddressOf(), TXT_FUNCTION_ALREADY_EXIST, r, c); break; } } } } // Register the function module->AddScriptFunction(file->idx, funcID, name.AddressOf(), returnType, parameterTypes.AddressOf(), inOutFlags.AddressOf(), (asUINT)parameterTypes.GetLength(), isInterface, objType, isConstMethod, isGlobalFunction); if( objType ) { if( isConstructor ) { if( parameterTypes.GetLength() == 0 ) { // Overload the default constructor objType->beh.construct = funcID; objType->beh.constructors[0] = funcID; // Register the default factory as well objType->beh.factory = engine->GetNextScriptFunctionId(); objType->beh.factories[0] = objType->beh.factory; asCDataType dt = asCDataType::CreateObjectHandle(objType, false); module->AddScriptFunction(file->idx, objType->beh.factory, name.AddressOf(), dt, parameterTypes.AddressOf(), inOutFlags.AddressOf(), (asUINT)parameterTypes.GetLength(), false); // Add a dummy function to the module so that it doesn't mix up the func Ids functions.PushLast(0); // Compile the factory immediately asCCompiler compiler(engine); compiler.CompileFactory(this, file, engine->scriptFunctions[objType->beh.factory]); } else { objType->beh.constructors.PushLast(funcID); // TODO: This is almost identical to above if block. Should be reduced to common code. // Register the factory as well int factoryId = engine->GetNextScriptFunctionId(); objType->beh.factories.PushLast(factoryId); asCDataType dt = asCDataType::CreateObjectHandle(objType, false); module->AddScriptFunction(file->idx, factoryId, name.AddressOf(), dt, parameterTypes.AddressOf(), inOutFlags.AddressOf(), (asUINT)parameterTypes.GetLength(), false); // Add a dummy function to the module so that it doesn't mix up the fund Ids functions.PushLast(0); // Compile the factory immediately asCCompiler compiler(engine); compiler.CompileFactory(this, file, engine->scriptFunctions[factoryId]); } } else if( isDestructor ) objType->beh.destruct = funcID; else objType->methods.PushLast(funcID); } // We need to delete the node already if this is an interface method if( isInterface && node ) { node->Destroy(engine); } return 0; } int asCBuilder::RegisterImportedFunction(int importID, asCScriptNode *node, asCScriptCode *file) { // Find name asCScriptNode *f = node->firstChild; asCScriptNode *n = f->firstChild->next->next; // Check for name conflicts asCString name(&file->code[n->tokenPos], n->tokenLength); CheckNameConflict(name.AddressOf(), n, file); // Initialize a script function object for registration asCDataType returnType; returnType = CreateDataTypeFromNode(f->firstChild, file); returnType = ModifyDataTypeFromNode(returnType, f->firstChild->next, file, 0, 0); // Count the parameters int count = 0; asCScriptNode *c = n->next->firstChild; while( c ) { count++; c = c->next->next; if( c && c->nodeType == snIdentifier ) c = c->next; } asCArray<asCDataType> parameterTypes(count); asCArray<asETypeModifiers> inOutFlags(count); n = n->next->firstChild; while( n ) { asETypeModifiers inOutFlag; asCDataType type = CreateDataTypeFromNode(n, file); type = ModifyDataTypeFromNode(type, n->next, file, &inOutFlag, 0); // Store the parameter type n = n->next->next; parameterTypes.PushLast(type); inOutFlags.PushLast(inOutFlag); // Move to next parameter if( n && n->nodeType == snIdentifier ) n = n->next; } // Check that the same function hasn't been registered already asCArray<int> funcs; GetFunctionDescriptions(name.AddressOf(), funcs); if( funcs.GetLength() ) { for( asUINT n = 0; n < funcs.GetLength(); ++n ) { asCScriptFunction *func = GetFunctionDescription(funcs[n]); // TODO: Isn't the name guaranteed to be equal, because of GetFunctionDescriptions()? if( name == func->name && parameterTypes.GetLength() == func->parameterTypes.GetLength() ) { bool match = true; for( asUINT p = 0; p < parameterTypes.GetLength(); ++p ) { if( parameterTypes[p] != func->parameterTypes[p] ) { match = false; break; } } if( match ) { int r, c; file->ConvertPosToRowCol(node->tokenPos, &r, &c); WriteError(file->name.AddressOf(), TXT_FUNCTION_ALREADY_EXIST, r, c); break; } } } } // Read the module name as well n = node->firstChild->next; asCString moduleName; moduleName.Assign(&file->code[n->tokenPos+1], n->tokenLength-2); node->Destroy(engine); // Register the function module->AddImportedFunction(importID, name.AddressOf(), returnType, parameterTypes.AddressOf(), inOutFlags.AddressOf(), (asUINT)parameterTypes.GetLength(), moduleName); return 0; } asCScriptFunction *asCBuilder::GetFunctionDescription(int id) { // TODO: This should be improved // Get the description from the engine if( (id & 0xFFFF0000) == 0 ) return engine->scriptFunctions[id]; else return module->importedFunctions[id & 0xFFFF]; } void asCBuilder::GetFunctionDescriptions(const char *name, asCArray<int> &funcs) { asUINT n; // TODO: optimize: Improve linear search for( n = 0; n < module->scriptFunctions.GetLength(); n++ ) { if( module->scriptFunctions[n]->name == name && module->scriptFunctions[n]->objectType == 0 ) funcs.PushLast(module->scriptFunctions[n]->id); } // TODO: optimize: Improve linear search for( n = 0; n < module->importedFunctions.GetLength(); n++ ) { if( module->importedFunctions[n]->name == name ) funcs.PushLast(module->importedFunctions[n]->id); } // TODO: optimize: Improve linear search for( n = 0; n < engine->scriptFunctions.GetLength(); n++ ) { if( engine->scriptFunctions[n] && engine->scriptFunctions[n]->funcType == asFUNC_SYSTEM && engine->scriptFunctions[n]->objectType == 0 && engine->scriptFunctions[n]->name == name ) { // Find the config group for the global function asCConfigGroup *group = engine->FindConfigGroupForFunction(engine->scriptFunctions[n]->id); if( !group || group->HasModuleAccess(module->name.AddressOf()) ) funcs.PushLast(engine->scriptFunctions[n]->id); } } } void asCBuilder::GetObjectMethodDescriptions(const char *name, asCObjectType *objectType, asCArray<int> &methods, bool objIsConst, const asCString &scope) { if( scope != "" ) { // Find the base class with the specified scope while( objectType && objectType->name != scope ) objectType = objectType->derivedFrom; // If the scope is not any of the base classes, then return no methods if( objectType == 0 ) return; } // TODO: optimize: Improve linear search if( objIsConst ) { // Only add const methods to the list for( asUINT n = 0; n < objectType->methods.GetLength(); n++ ) { if( engine->scriptFunctions[objectType->methods[n]]->name == name && engine->scriptFunctions[objectType->methods[n]]->isReadOnly ) { // When the scope is defined the returned methods should be the true methods, not the virtual method stubs if( scope == "" ) methods.PushLast(engine->scriptFunctions[objectType->methods[n]]->id); else { asCScriptFunction *virtFunc = engine->scriptFunctions[objectType->methods[n]]; asCScriptFunction *realFunc = objectType->virtualFunctionTable[virtFunc->vfTableIdx]; methods.PushLast(realFunc->id); } } } } else { // TODO: Prefer non-const over const for( asUINT n = 0; n < objectType->methods.GetLength(); n++ ) { if( engine->scriptFunctions[objectType->methods[n]]->name == name ) { // When the scope is defined the returned methods should be the true methods, not the virtual method stubs if( scope == "" ) methods.PushLast(engine->scriptFunctions[objectType->methods[n]]->id); else { asCScriptFunction *virtFunc = engine->scriptFunctions[objectType->methods[n]]; asCScriptFunction *realFunc = objectType->virtualFunctionTable[virtFunc->vfTableIdx]; methods.PushLast(realFunc->id); } } } } } void asCBuilder::WriteInfo(const char *scriptname, const char *message, int r, int c, bool pre) { // Need to store the pre message in a structure if( pre ) { preMessage.isSet = true; preMessage.c = c; preMessage.r = r; preMessage.message = message; } else { preMessage.isSet = false; engine->WriteMessage(scriptname, r, c, asMSGTYPE_INFORMATION, message); } } void asCBuilder::WriteError(const char *scriptname, const char *message, int r, int c) { numErrors++; // Need to pass the preMessage first if( preMessage.isSet ) WriteInfo(scriptname, preMessage.message.AddressOf(), preMessage.r, preMessage.c, false); engine->WriteMessage(scriptname, r, c, asMSGTYPE_ERROR, message); } void asCBuilder::WriteWarning(const char *scriptname, const char *message, int r, int c) { numWarnings++; // Need to pass the preMessage first if( preMessage.isSet ) WriteInfo(scriptname, preMessage.message.AddressOf(), preMessage.r, preMessage.c, false); engine->WriteMessage(scriptname, r, c, asMSGTYPE_WARNING, message); } asCDataType asCBuilder::CreateDataTypeFromNode(asCScriptNode *node, asCScriptCode *file, bool acceptHandleForScope, asCObjectType *templateType) { asASSERT(node->nodeType == snDataType); asCDataType dt; asCScriptNode *n = node->firstChild; bool isConst = false; bool isImplicitHandle = false; if( n->tokenType == ttConst ) { isConst = true; n = n->next; } if( n->tokenType == ttIdentifier ) { asCString str; str.Assign(&file->code[n->tokenPos], n->tokenLength); asCObjectType *ot = 0; // If this is for a template type, then we must first determine if the // identifier matches any of the template subtypes // TODO: template: it should be possible to have more than one subtypes if( templateType && (templateType->flags & asOBJ_TEMPLATE) && str == templateType->templateSubType.GetObjectType()->name ) ot = templateType->templateSubType.GetObjectType(); if( ot == 0 ) ot = GetObjectType(str.AddressOf()); if( ot == 0 ) { asCString msg; msg.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE, (const char *)str.AddressOf()); int r, c; file->ConvertPosToRowCol(n->tokenPos, &r, &c); WriteError(file->name.AddressOf(), msg.AddressOf(), r, c); dt.SetTokenType(ttInt); } else { if( ot->flags & asOBJ_IMPLICIT_HANDLE ) isImplicitHandle = true; // Find the config group for the object type asCConfigGroup *group = engine->FindConfigGroupForObjectType(ot); if( !module || !group || group->HasModuleAccess(module->name.AddressOf()) ) { if(asOBJ_TYPEDEF == (ot->flags & asOBJ_TYPEDEF)) { // TODO: typedef: A typedef should be considered different from the original type (though with implicit conversions between the two) // Create primitive data type based on object flags dt = ot->templateSubType; dt.MakeReadOnly(isConst); } else { if( ot->flags & asOBJ_TEMPLATE ) { n = n->next; // Check if the subtype is a type or the template's subtype // if it is the template's subtype then this is the actual template type, // orderwise it is a template instance. asCDataType subType = CreateDataTypeFromNode(n, file, false, ot); if( subType.GetObjectType() != ot->templateSubType.GetObjectType() ) { // This is a template instance // Need to find the correct object type asCObjectType *otInstance = engine->GetTemplateInstanceType(ot, subType); if( !otInstance ) { asCString msg; msg.Format(TXT_CANNOT_INSTANCIATE_TEMPLATE_s_WITH_s, ot->name.AddressOf(), subType.Format().AddressOf()); int r, c; file->ConvertPosToRowCol(n->tokenPos, &r, &c); WriteError(file->name.AddressOf(), msg.AddressOf(), r, c); } ot = otInstance; } } // Create object data type if( ot ) dt = asCDataType::CreateObject(ot, isConst); else dt = asCDataType::CreatePrimitive(ttInt, isConst); } } else { asCString msg; msg.Format(TXT_TYPE_s_NOT_AVAILABLE_FOR_MODULE, (const char *)str.AddressOf()); int r, c; file->ConvertPosToRowCol(n->tokenPos, &r, &c); WriteError(file->name.AddressOf(), msg.AddressOf(), r, c); dt.SetTokenType(ttInt); } } } else { // Create primitive data type dt = asCDataType::CreatePrimitive(n->tokenType, isConst); } // Determine array dimensions and object handles n = n->next; while( n && (n->tokenType == ttOpenBracket || n->tokenType == ttHandle) ) { if( n->tokenType == ttOpenBracket ) { // Make sure the sub type can be instanciated if( !dt.CanBeInstanciated() ) { int r, c; file->ConvertPosToRowCol(n->tokenPos, &r, &c); asCString str; // TODO: Change to "Array sub type cannot be 'type'" str.Format(TXT_DATA_TYPE_CANT_BE_s, dt.Format().AddressOf()); WriteError(file->name.AddressOf(), str.AddressOf(), r, c); } // Make the type an array (or multidimensional array) if( dt.MakeArray(engine) < 0 ) { int r, c; file->ConvertPosToRowCol(n->tokenPos, &r, &c); WriteError(file->name.AddressOf(), TXT_TOO_MANY_ARRAY_DIMENSIONS, r, c); break; } } else { // Make the type a handle if( dt.MakeHandle(true, acceptHandleForScope) < 0 ) { int r, c; file->ConvertPosToRowCol(n->tokenPos, &r, &c); WriteError(file->name.AddressOf(), TXT_OBJECT_HANDLE_NOT_SUPPORTED, r, c); break; } } n = n->next; } if( isImplicitHandle ) { // Make the type a handle if( dt.MakeHandle(true, acceptHandleForScope) < 0 ) { int r, c; file->ConvertPosToRowCol(n->tokenPos, &r, &c); WriteError(file->name.AddressOf(), TXT_OBJECT_HANDLE_NOT_SUPPORTED, r, c); } } return dt; } asCDataType asCBuilder::ModifyDataTypeFromNode(const asCDataType &type, asCScriptNode *node, asCScriptCode *file, asETypeModifiers *inOutFlags, bool *autoHandle) { asCDataType dt = type; if( inOutFlags ) *inOutFlags = asTM_NONE; // Is the argument sent by reference? asCScriptNode *n = node->firstChild; if( n && n->tokenType == ttAmp ) { dt.MakeReference(true); n = n->next; if( n ) { if( inOutFlags ) { if( n->tokenType == ttIn ) *inOutFlags = asTM_INREF; else if( n->tokenType == ttOut ) *inOutFlags = asTM_OUTREF; else if( n->tokenType == ttInOut ) *inOutFlags = asTM_INOUTREF; else asASSERT(false); } n = n->next; } else { if( inOutFlags ) *inOutFlags = asTM_INOUTREF; // ttInOut } if( !engine->ep.allowUnsafeReferences && inOutFlags && *inOutFlags == asTM_INOUTREF ) { // Verify that the base type support &inout parameter types if( !dt.IsObject() || dt.IsObjectHandle() || !dt.GetObjectType()->beh.addref || !dt.GetObjectType()->beh.release ) { int r, c; file->ConvertPosToRowCol(node->firstChild->tokenPos, &r, &c); WriteError(file->name.AddressOf(), TXT_ONLY_OBJECTS_MAY_USE_REF_INOUT, r, c); } } } if( autoHandle ) *autoHandle = false; if( n && n->tokenType == ttPlus ) { if( autoHandle ) *autoHandle = true; } return dt; } const asCString &asCBuilder::GetConstantString(int strID) { return module->GetConstantString(strID); } asCObjectType *asCBuilder::GetObjectType(const char *type) { // TODO: Only search in config groups to which the module has access asCObjectType *ot = engine->GetObjectType(type); if( !ot && module ) ot = module->GetObjectType(type); return ot; } int asCBuilder::GetEnumValueFromObjectType(asCObjectType *objType, const char *name, asCDataType &outDt, asDWORD &outValue) { if( !objType || !(objType->flags & asOBJ_ENUM) ) return 0; for( asUINT n = 0; n < objType->enumValues.GetLength(); ++n ) { if( objType->enumValues[n]->name == name ) { outDt = asCDataType::CreateObject(objType, true); outValue = objType->enumValues[n]->value; return 1; } } return 0; } int asCBuilder::GetEnumValue(const char *name, asCDataType &outDt, asDWORD &outValue) { bool found = false; // Search all available enum types asUINT t; for( t = 0; t < engine->objectTypes.GetLength(); t++ ) { asCObjectType *ot = engine->objectTypes[t]; if( GetEnumValueFromObjectType( ot, name, outDt, outValue ) ) { if( !found ) { found = true; } else { // Found more than one value in different enum types return 2; } } } for( t = 0; t < module->enumTypes.GetLength(); t++ ) { asCObjectType *ot = module->enumTypes[t]; if( GetEnumValueFromObjectType( ot, name, outDt, outValue ) ) { if( !found ) { found = true; } else { // Found more than one value in different enum types return 2; } } } if( found ) return 1; // Didn't find any value return 0; } END_AS_NAMESPACE
[ [ [ 1, 2670 ] ] ]
9719db358a1dbd2e84eadb08af917033e153c7c8
c1a2953285f2a6ac7d903059b7ea6480a7e2228e
/deitel/ch07/Fig07_05/fig07_05.cpp
1ed3eae9950e4b83e85eea8ddc229bc0af3de345
[]
no_license
tecmilenio/computacion2
728ac47299c1a4066b6140cebc9668bf1121053a
a1387e0f7f11c767574fcba608d94e5d61b7f36c
refs/heads/master
2016-09-06T19:17:29.842053
2008-09-28T04:27:56
2008-09-28T04:27:56
50,540
4
3
null
null
null
null
UTF-8
C++
false
false
1,830
cpp
// Fig. 7.5: fig07_05.cpp // Set array s to the even integers from 2 to 20. #include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; int main() { // constant variable can be used to specify array size const int arraySize = 10; // must initialize in declaration int s[ arraySize ]; // array s has 10 elements for ( int i = 0; i < arraySize; i++ ) // set the values s[ i ] = 2 + 2 * i; cout << "Element" << setw( 13 ) << "Value" << endl; // output contents of array s in tabular format for ( int j = 0; j < arraySize; j++ ) cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl; return 0; // indicates successful termination } // end main /************************************************************************** * (C) Copyright 1992-2008 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * **************************************************************************/
[ [ [ 1, 43 ] ] ]
43b3c7a92351575ab44e0abcc71c3066fc40d039
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/Launcher/StdAfx.cpp
12d0ab3d015a648b351d911820679d5555ac8fa0
[]
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
295
cpp
// stdafx.cpp : source file that includes just the standard includes // Launcher.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
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 8 ] ] ]
7d06e6551b1d2aa73deb7d1f7470fcfe17edbcf4
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/spirit/fusion/test/fold_tests.cpp
6cf436261861f1082d9988b7824cd6d033c72b95
[ "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
2,897
cpp
/*============================================================================= Copyright (c) 2003 Joel de Guzman Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #include <boost/detail/lightweight_test.hpp> #include <boost/spirit/fusion/sequence/tuple.hpp> #include <boost/spirit/fusion/sequence/io.hpp> #include <boost/spirit/fusion/algorithm/fold.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/next.hpp> #include <boost/mpl/int.hpp> #include <boost/mpl/vector.hpp> using boost::mpl::if_; using boost::mpl::int_; using boost::is_same; struct add_ints_only { template <typename T, typename State> struct apply { typedef State type; }; template <typename T, typename State> State const& operator()(T const& x, State const& state) const { return state; } int operator()(int x, int state) const { return x + state; } }; struct count_ints { template <typename T, typename CountT> struct apply { typedef typename if_< is_same<T, int> , typename boost::mpl::next<CountT>::type , CountT >::type type; }; template <typename T, typename CountT> typename apply<T, CountT>::type operator()(T const&, CountT const&) const { typedef typename apply<T, CountT>::type result; return result(); } }; int main() { using namespace boost::fusion; using boost::mpl::vector; namespace fusion = boost::fusion; /// Testing fold { typedef tuple<int, char, int, double> tuple_type; tuple_type t(12345, 'x', 678910, 3.36); int result = fold(t, 0, add_ints_only()); std::cout << result << std::endl; BOOST_TEST(result == 12345+678910); } { typedef tuple<int> tuple_type; tuple_type t(12345); int n = fusion::fold(t, FUSION_INT(0)(), count_ints()); std::cout << n << std::endl; BOOST_TEST(n == 1); } { typedef tuple<int, char, int, double, int> tuple_type; tuple_type t(12345, 'x', 678910, 3.36, 8756); int n = fusion::fold(t, FUSION_INT(0)(), count_ints()); std::cout << n << std::endl; BOOST_TEST(n == 3); } { typedef vector<int, char, int, double, int> mpl_vec; int n = fusion::fold(mpl_vec(), FUSION_INT(0)(), count_ints()); std::cout << n << std::endl; BOOST_TEST(n == 3); } return boost::report_errors(); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 111 ] ] ]
1e1dbfbb195c4c82baed0558b0e84df7a5afb8ad
faacd0003e0c749daea18398b064e16363ea8340
/3rdparty/phonon/mediaobjectinterface.h
03340b7df8d2a1da04b2131f77dd6f07af41b6b4
[]
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
9,191
h
/* This file is part of the KDE project Copyright (C) 2006-2007 Matthias Kretz <[email protected]> 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) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Trolltech ASA (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. 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, see <http://www.gnu.org/licenses/>. */ #ifndef PHONON_MEDIAOBJECTINTERFACE_H #define PHONON_MEDIAOBJECTINTERFACE_H #include "mediaobject.h" #include <QtCore/QObject> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE namespace Phonon { class StreamInterface; /** \class MediaObjectInterface mediaobjectinterface.h Phonon/MediaObjectInterface * \short Backend interface for media sources. * * The backend implementation has to provide two signals, that are not defined * in this interface: * <ul> * <li>\anchor phonon_MediaObjectInterface_stateChanged * <b>void stateChanged(\ref Phonon::State newstate, \ref Phonon::State oldstate)</b> * * Emitted when the state of the MediaObject has changed. * In case you're not interested in the old state you can also * connect to a slot that only has one State argument. * * \param newstate The state the Player is in now. * \param oldstate The state the Player was in before. * </li> * <li>\anchor phonon_MediaObjectInterface_tick * <b>void tick(qint64 time)</b> * * This signal gets emitted every tickInterval milliseconds. * * \param time The position of the media file in milliseconds. * * \see setTickInterval() * \see tickInterval() * </li> * </ul> * * \author Matthias Kretz <[email protected]> * \see MediaObject */ class MediaObjectInterface { public: virtual ~MediaObjectInterface() {} /** * Requests the playback to start. * * This method is only called if the state transition to \ref PlayingState is possible. * * The backend should react immediately * by either going into \ref PlayingState or \ref BufferingState if the * former is not possible. */ virtual void play() = 0; /** * Requests the playback to pause. * * This method is only called if the state transition to \ref PausedState is possible. * * The backend should react as fast as possible. Go to \ref PausedState * as soon as playback is paused. */ virtual void pause() = 0; /** * Requests the playback to be stopped. * * This method is only called if the state transition to \ref StoppedState is possible. * * The backend should react as fast as possible. Go to \ref StoppedState * as soon as playback is stopped. * * A subsequent call to play() will start playback at the beginning of * the media. */ virtual void stop() = 0; /** * Requests the playback to be seeked to the given time. * * The backend does not have to finish seeking while in this function * (i.e. the backend does not need to block the thread until the seek is * finished; even worse it might lead to deadlocks when using a * ByteStream which gets its data from the thread this function would * block). * * As soon as the seek is done the currentTime() function and * the tick() signal will report it. * * \param milliseconds The time where playback should seek to in * milliseconds. */ virtual void seek(qint64 milliseconds) = 0; /** * Return the time interval in milliseconds between two ticks. * * \returns Returns the tick interval that it was set to (might not * be the same as you asked for). */ virtual qint32 tickInterval() const = 0; /** * Change the interval the tick signal is emitted. If you set \p * interval to 0 the signal gets disabled. * * \param interval tick interval in milliseconds * * \returns Returns the tick interval that it was set to (might not * be the same as you asked for). */ virtual void setTickInterval(qint32 interval) = 0; /** * Check whether the media data includes a video stream. * * \return returns \p true if the media contains video data */ virtual bool hasVideo() const = 0; /** * If the current media may be seeked returns true. * * \returns whether the current media may be seeked. */ virtual bool isSeekable() const = 0; /** * Get the current time (in milliseconds) of the file currently being played. */ virtual qint64 currentTime() const = 0; /** * Get the current state. */ virtual Phonon::State state() const = 0; /** * A translated string describing the error. */ virtual QString errorString() const = 0; /** * Tells your program what to do about the error. * * \see Phonon::ErrorType */ virtual Phonon::ErrorType errorType() const = 0; /** * Returns the total time of the media in milliseconds. * * If the total time is not know return -1. Do not block until it is * known, instead emit the totalTimeChanged signal as soon as the total * time is known or changes. */ virtual qint64 totalTime() const = 0; /** * Returns the current source. */ virtual MediaSource source() const = 0; /** * Sets the current source. When this function is called the MediaObject is * expected to stop all current activity and start loading the new * source (i.e. go into LoadingState). * * It is expected that the * backend now starts preloading the media data, filling the audio * and video buffers and making all media meta data available. It * will also trigger the totalTimeChanged signal. * * If the backend does not know how to handle the source it needs to * change state to Phonon::ErrorState. Don't bother about handling KIO * URLs. It is enough to handle AbstractMediaStream sources correctly. * * \warning Keep the MediaSource object around as long as the backend * uses the AbstractMediaStream returned by the MediaSource. In case * that no other reference to the MediaSource exists and it is set to * MediaSource::autoDelete, the AbstractMediaStream is deleted when the * last MediaSource ref is deleted. */ virtual void setSource(const MediaSource &) = 0; /** * Sets the next source to be used for transitions. When a next source * is set playback should continue with the new source. In that case * finished and prefinishMarkReached are not emitted. * * \param source The source to transition to (crossfade/gapless/gap). If * \p source is an invalid MediaSource object then the queue is empty * and the playback should stop normally. * * \warning Keep the MediaSource object around as long as the backend * uses the AbstractMediaStream returned by the MediaSource. In case * that no other reference to the MediaSource exists and it is set to * MediaSource::autoDelete, the AbstractMediaStream is deleted when the * last MediaSource ref is deleted. */ virtual void setNextSource(const MediaSource &source) = 0; virtual qint64 remainingTime() const { return totalTime() - currentTime(); } virtual qint32 prefinishMark() const = 0; virtual void setPrefinishMark(qint32) = 0; virtual qint32 transitionTime() const = 0; virtual void setTransitionTime(qint32) = 0; }; } Q_DECLARE_INTERFACE(Phonon::MediaObjectInterface, "MediaObjectInterface3.phonon.kde.org") QT_END_NAMESPACE QT_END_HEADER #endif // PHONON_MEDIAOBJECTINTERFACE_H // vim: sw=4 ts=4 tw=80
[ "futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9" ]
[ [ [ 1, 242 ] ] ]
bca80c0e10354d31b03880b9414a8df8f989bdb2
0508304aeb1d50db67a090eecb7436b13f06583d
/nemo/headers/private/print/libprint/AboutBox.h
be7d88189b6c2856f131edc2a699c8f7427e664f
[]
no_license
BackupTheBerlios/nemo
229a7c64901162cf8359f7ddb3a7dd4d05763196
1511021681e9efd91e394191bb00313f0112c628
refs/heads/master
2016-08-03T16:33:46.947041
2004-04-28T01:51:58
2004-04-28T01:51:58
40,045,282
0
0
null
null
null
null
UTF-8
C++
false
false
341
h
/* * AboutBox.h * Copyright 1999-2000 Y.Takagi. All Rights Reserved. */ #ifndef __ABOUTBOX_H #define __ABOUTBOX_H #include <Application.h> class AboutBox : public BApplication { public: AboutBox(const char *signature, const char *driver_name, const char *version, const char *copyright); }; #endif /* __ABOUTBOX_H */
[ "fadi_edward" ]
[ [ [ 1, 16 ] ] ]
b1399ab3dbdcc2b52d9ca85427621fd93abbe995
5748d8e5ab80776e6f565f0dd1f5029d4af5b65e
/codeforces/4/A.cpp
0440874c50d9f4b7994a49ac4a0e9009fa52698c
[]
no_license
lokiysh/cp
f50394a98eec42aa4e9ae997aa4852253fff012f
99cbf19c9db16f51de5a68a8c4989f5de36678c8
refs/heads/master
2023-02-10T21:18:51.987872
2011-07-22T13:04:00
2021-01-11T02:39:17
328,587,177
0
0
null
null
null
null
UTF-8
C++
false
false
141
cpp
#include<stdio.h> int main() { int n; scanf("%d",&n); if(n%2==1||n<=2) printf("NO"); else printf("YES"); return 0; }
[ [ [ 1, 9 ] ] ]
2e200958915308747e2cddfd507003b0ff11c558
c70941413b8f7bf90173533115c148411c868bad
/plugins/AS3Plugin/src/vtxas3SimpleButton.cpp
5979d1d5bdbc43d4d18ee3e84ef23c730ca66c29
[]
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,813
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 "vtxas3SimpleButton.h" #include "vtxButton.h" namespace vtx { namespace as3 { //----------------------------------------------------------------------- void SimpleButton::setNativeObject(Instance* inst) { //InteractiveObject::setNativeObject(inst); //mButton = static_cast<vtx::Button*>(inst); } //----------------------------------------------------------------------- }}
[ "stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a" ]
[ [ [ 1, 41 ] ] ]
44b751474a50d015d48590db9795acdfed970be3
2c9e29d0cdae3e532ff969c0de530b5b8084b61e
/psp/video_hardware_light.cpp
c6ff9451cb0460c5dfcd0bcfeb19fd99a517aa78
[]
no_license
Sondro/kurok
1695a976700f6c9732a761d33d092a679518e23b
59da1adb94e1132c5a2215b308280bacd7a3c812
refs/heads/master
2022-02-01T17:41:12.584690
2009-08-03T01:19:05
2009-08-03T01:19:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,871
cpp
/* Copyright (C) 1996-1997 Id Software, Inc. Copyright (C) 2007 Peter Mackay and Chris Swindle. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // r_light.c extern "C" { #include "../quakedef.h" } int r_dlightframecount; /* ================== R_AnimateLight ================== */ void R_AnimateLight (void) { int i,j,k; // // light animations // 'm' is normal light, 'a' is no light, 'z' is double bright i = (int)(cl.time*10); for (j=0 ; j<MAX_LIGHTSTYLES ; j++) { if (!cl_lightstyle[j].length) { d_lightstylevalue[j] = 256; continue; } k = i % cl_lightstyle[j].length; k = cl_lightstyle[j].map[k] - 'a'; k = k*22; d_lightstylevalue[j] = k; } } /* ============================================================================= DYNAMIC LIGHTS BLEND RENDERING ============================================================================= */ static void AddLightBlend (float r, float g, float b, float a2) { float a; v_blend[3] = a = v_blend[3] + a2*(1-v_blend[3]); a2 = a2/a; v_blend[0] = v_blend[1]*(1-a2) + r*a2; v_blend[1] = v_blend[1]*(1-a2) + g*a2; v_blend[2] = v_blend[2]*(1-a2) + b*a2; } static void R_RenderDlight (dlight_t *light) { /* // int i, j; // float a; vec3_t v; float rad; rad = light->radius * 0.35; VectorSubtract (light->origin, r_origin, v); if (Length (v) < rad) { // view is inside the dlight AddLightBlend (1, 0.5, 0, light->radius * 0.0003); return; } */ /* glBegin (GL_TRIANGLE_FAN); glColor3f (0.2,0.1,0.0); for (i=0 ; i<3 ; i++) v[i] = light->origin[i] - vpn[i]*rad; glVertex3fv (v); glColor3f (0,0,0); for (i=16 ; i>=0 ; i--) { a = i/16.0 * M_PI*2; for (j=0 ; j<3 ; j++) v[j] = light->origin[j] + vright[j]*cosf(a)*rad + vup[j]*sinf(a)*rad; glVertex3fv (v); } glEnd (); */ } /* ============= R_RenderDlights ============= */ void R_RenderDlights (void) { // int i; // dlight_t *l; r_dlightframecount = r_framecount + 1; // because the count hasn't // advanced yet for this frame /*glDepthMask (0); glDisable (GL_TEXTURE_2D); glShadeModel (GL_SMOOTH); glEnable (GL_BLEND); glBlendFunc (GL_ONE, GL_ONE); l = cl_dlights; for (i=0 ; i<MAX_DLIGHTS ; i++, l++) { if (l->die < cl.time || !l->radius) continue; R_RenderDlight (l); } glColor3f (1,1,1); glDisable (GL_BLEND); glEnable (GL_TEXTURE_2D); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDepthMask (1);*/ } /* ============================================================================= DYNAMIC LIGHTS ============================================================================= */ /* ============= R_MarkLights ============= */ /* void R_MarkLights (dlight_t *light, int bit, mnode_t *node) { mplane_t *splitplane; float dist; msurface_t *surf; int i; if (node->contents < 0) return; splitplane = node->plane; dist = DotProduct (light->origin, splitplane->normal) - splitplane->dist; if (dist > light->radius) { R_MarkLights (light, bit, node->children[0]); return; } if (dist < -light->radius) { R_MarkLights (light, bit, node->children[1]); return; } // mark the polygons surf = cl.worldmodel->surfaces + node->firstsurface; for (i=0 ; i<node->numsurfaces ; i++, surf++) { if (surf->dlightframe != r_dlightframecount) { surf->dlightbits = 0; surf->dlightframe = r_dlightframecount; } surf->dlightbits |= bit; } R_MarkLights (light, bit, node->children[0]); R_MarkLights (light, bit, node->children[1]); } */ void R_MarkLights (dlight_t *light, int bit, mnode_t *node) { mplane_t *splitplane; float dist, l, maxdist; msurface_t *surf; int i, j, s, t, sidebit; vec3_t impact; loc0: if (node->contents < 0) return; splitplane = node->plane; // dist = PlaneDiff(light->origin, splitplane); if (splitplane->type < 3) dist = light->origin[splitplane->type] - splitplane->dist; else dist = DotProduct (light->origin, splitplane->normal) - splitplane->dist; if (dist > light->radius) { node = node->children[0]; goto loc0; } if (dist < -light->radius) { node = node->children[1]; goto loc0; } maxdist = light->radius * light->radius; // mark the polygons surf = cl.worldmodel->surfaces + node->firstsurface; for (i=0 ; i<node->numsurfaces ; i++, surf++) { dist = DotProduct (light->origin, surf->plane->normal) - surf->plane->dist; // JT030305 - fix light bleed through if (dist >= 0) sidebit = 0; else sidebit = SURF_PLANEBACK; if ( (surf->flags & SURF_PLANEBACK) != sidebit ) //Discoloda continue; //Discoloda for (j=0 ; j<3 ; j++) impact[j] = light->origin[j] - surf->plane->normal[j]*dist; // clamp center of light to corner and check brightness l = DotProduct(impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0]; s = l + 0.5; s = bound(0, s, surf->extents[0]); s = l - s; l = DotProduct(impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1]; t = l + 0.5; t = bound(0, t, surf->extents[1]); t = l - t; // compare to minimum light if ((s*s + t*t + dist*dist) < maxdist) { if (surf->dlightframe != r_dlightframecount) // not dynamic until now { surf->dlightbits = bit; surf->dlightframe = r_dlightframecount; } else // already dynamic { surf->dlightbits |= bit; } } } if (node->children[0]->contents >= 0) R_MarkLights (light, bit, node->children[0]); if (node->children[1]->contents >= 0) R_MarkLights (light, bit, node->children[1]); } /* ============= R_PushDlights ============= */ void R_PushDlights (void) { int i; dlight_t *l; r_dlightframecount = r_framecount + 1; // because the count hasn't // advanced yet for this frame l = cl_dlights; for (i=0 ; i<MAX_DLIGHTS ; i++, l++) { if (l->die < cl.time || !l->radius) continue; R_MarkLights ( l, 1<<i, cl.worldmodel->nodes ); } } /* ============================================================================= LIGHT SAMPLING ============================================================================= */ mplane_t *lightplane; vec3_t lightspot; /* int RecursiveLightPoint (mnode_t *node, vec3_t start, vec3_t end) { int r; float front, back, frac; int side; mplane_t *plane; vec3_t mid; msurface_t *surf; int s, t, ds, dt; int i; mtexinfo_t *tex; byte *lightmap; unsigned scale; int maps; if (node->contents < 0) return -1; // didn't hit anything // calculate mid point // FIXME: optimize for axial plane = node->plane; front = DotProduct (start, plane->normal) - plane->dist; back = DotProduct (end, plane->normal) - plane->dist; side = front < 0; if ( (back < 0) == side) return RecursiveLightPoint (node->children[side], start, end); frac = front / (front-back); mid[0] = start[0] + (end[0] - start[0])*frac; mid[1] = start[1] + (end[1] - start[1])*frac; mid[2] = start[2] + (end[2] - start[2])*frac; // go down front side r = RecursiveLightPoint (node->children[side], start, mid); if (r >= 0) return r; // hit something if ( (back < 0) == side ) return -1; // didn't hit anuthing // check for impact on this node VectorCopy (mid, lightspot); lightplane = plane; surf = cl.worldmodel->surfaces + node->firstsurface; for (i=0 ; i<node->numsurfaces ; i++, surf++) { if (surf->flags & SURF_DRAWTILED) continue; // no lightmaps tex = surf->texinfo; s = DotProduct (mid, tex->vecs[0]) + tex->vecs[0][3]; t = DotProduct (mid, tex->vecs[1]) + tex->vecs[1][3];; if (s < surf->texturemins[0] || t < surf->texturemins[1]) continue; ds = s - surf->texturemins[0]; dt = t - surf->texturemins[1]; if ( ds > surf->extents[0] || dt > surf->extents[1] ) continue; if (!surf->samples) return 0; ds >>= 4; dt >>= 4; lightmap = surf->samples; r = 0; if (lightmap) { lightmap += dt * ((surf->extents[0]>>4)+1) + ds; for (maps = 0 ; maps < MAXLIGHTMAPS && surf->styles[maps] != 255 ; maps++) { scale = d_lightstylevalue[surf->styles[maps]]; r += *lightmap * scale; lightmap += ((surf->extents[0]>>4)+1) * ((surf->extents[1]>>4)+1); } r >>= 8; } return r; } // go down back side return RecursiveLightPoint (node->children[!side], mid, end); } int R_LightPoint (vec3_t p) { vec3_t end; int r; if (!cl.worldmodel->lightdata) return 255; end[0] = p[0]; end[1] = p[1]; end[2] = p[2] - 2048; r = RecursiveLightPoint (cl.worldmodel->nodes, p, end); if (r == -1) r = 0; return r; } */ // LordHavoc: .lit support begin // LordHavoc: original code replaced entirely int RecursiveLightPoint (vec3_t color, mnode_t *node, vec3_t start, vec3_t end) { float front, back, frac; vec3_t mid; loc0: if (node->contents < 0) return false; // didn't hit anything // calculate mid point if (node->plane->type < 3) { front = start[node->plane->type] - node->plane->dist; back = end[node->plane->type] - node->plane->dist; } else { front = DotProduct(start, node->plane->normal) - node->plane->dist; back = DotProduct(end, node->plane->normal) - node->plane->dist; } // LordHavoc: optimized recursion if ((back < 0) == (front < 0)) // return RecursiveLightPoint (color, node->children[front < 0], start, end); { node = node->children[front < 0]; goto loc0; } frac = front / (front-back); mid[0] = start[0] + (end[0] - start[0])*frac; mid[1] = start[1] + (end[1] - start[1])*frac; mid[2] = start[2] + (end[2] - start[2])*frac; // go down front side if (RecursiveLightPoint (color, node->children[front < 0], start, mid)) return true; // hit something else { int i, ds, dt; msurface_t *surf; // check for impact on this node VectorCopy (mid, lightspot); lightplane = node->plane; surf = cl.worldmodel->surfaces + node->firstsurface; for (i = 0;i < node->numsurfaces;i++, surf++) { if (surf->flags & SURF_DRAWTILED) continue; // no lightmaps ds = (int) ((float) DotProduct (mid, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3]); dt = (int) ((float) DotProduct (mid, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3]); if (ds < surf->texturemins[0] || dt < surf->texturemins[1]) continue; ds -= surf->texturemins[0]; dt -= surf->texturemins[1]; if (ds > surf->extents[0] || dt > surf->extents[1]) continue; if (surf->samples) { // LordHavoc: enhanced to interpolate lighting byte *lightmap; int maps, line3, dsfrac = ds & 15, dtfrac = dt & 15, r00 = 0, g00 = 0, b00 = 0, r01 = 0, g01 = 0, b01 = 0, r10 = 0, g10 = 0, b10 = 0, r11 = 0, g11 = 0, b11 = 0; float scale; line3 = ((surf->extents[0]>>4)+1)*3; lightmap = surf->samples + ((dt>>4) * ((surf->extents[0]>>4)+1) + (ds>>4))*3; // LordHavoc: *3 for color for (maps = 0;maps < MAXLIGHTMAPS && surf->styles[maps] != 255;maps++) { scale = (float) d_lightstylevalue[surf->styles[maps]] * 1.0 / 256.0; r00 += (float) lightmap[ 0] * scale;g00 += (float) lightmap[ 1] * scale;b00 += (float) lightmap[2] * scale; r01 += (float) lightmap[ 3] * scale;g01 += (float) lightmap[ 4] * scale;b01 += (float) lightmap[5] * scale; r10 += (float) lightmap[line3+0] * scale;g10 += (float) lightmap[line3+1] * scale;b10 += (float) lightmap[line3+2] * scale; r11 += (float) lightmap[line3+3] * scale;g11 += (float) lightmap[line3+4] * scale;b11 += (float) lightmap[line3+5] * scale; lightmap += ((surf->extents[0]>>4)+1) * ((surf->extents[1]>>4)+1)*3; // LordHavoc: *3 for colored lighting } color[0] += (float) ((int) ((((((((r11-r10) * dsfrac) >> 4) + r10)-((((r01-r00) * dsfrac) >> 4) + r00)) * dtfrac) >> 4) + ((((r01-r00) * dsfrac) >> 4) + r00))); color[1] += (float) ((int) ((((((((g11-g10) * dsfrac) >> 4) + g10)-((((g01-g00) * dsfrac) >> 4) + g00)) * dtfrac) >> 4) + ((((g01-g00) * dsfrac) >> 4) + g00))); color[2] += (float) ((int) ((((((((b11-b10) * dsfrac) >> 4) + b10)-((((b01-b00) * dsfrac) >> 4) + b00)) * dtfrac) >> 4) + ((((b01-b00) * dsfrac) >> 4) + b00))); } return true; // success } // go down back side return RecursiveLightPoint (color, node->children[front >= 0], mid, end); } } vec3_t lightcolor; // LordHavoc: used by model rendering int R_LightPoint (vec3_t p) { vec3_t end; if (r_fullbright.value || !cl.worldmodel->lightdata) { lightcolor[0] = lightcolor[1] = lightcolor[2] = 255; return 255; } end[0] = p[0]; end[1] = p[1]; end[2] = p[2] - 2048; lightcolor[0] = lightcolor[1] = lightcolor[2] = 0; RecursiveLightPoint (lightcolor, cl.worldmodel->nodes, p, end); return ((lightcolor[0] + lightcolor[1] + lightcolor[2]) * (1.0f / 3.0f)); } // LordHavoc: .lit support end
[ [ [ 1, 554 ] ] ]
2c9298176ad97b253550a53c25a13d993a8f6bbd
e419dcb4a688d0c7b743c52c2d3c4c2edffc3ab8
/Raytrace/3rdparty/include/internal/optix_datatypes.h
08dafc541c0234fcb8ada2a40657e0415e3ec5be
[]
no_license
Jazzinghen/DTU-Rendering
d7f833c01836fadb4401133d8a5c17523e04bf49
b03692ce19d0ea765d61e88e19cd8113da99b7fe
refs/heads/master
2021-01-01T15:29:49.250365
2011-12-20T00:49:32
2011-12-20T00:49:32
2,505,173
0
0
null
null
null
null
UTF-8
C++
false
false
2,452
h
/* * Copyright (c) 2008 - 2009 NVIDIA Corporation. All rights reserved. * * NVIDIA Corporation and its licensors retain all intellectual property and proprietary * rights in and to this software, related documentation and any modifications thereto. * Any use, reproduction, disclosure or distribution of this software and related * documentation without an express license agreement from NVIDIA Corporation is strictly * prohibited. * * TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS* * AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, * INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY * SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT * LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF * BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR * INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF * SUCH DAMAGES */ #ifndef __optix_optix_datatypes_h__ #define __optix_optix_datatypes_h__ #include "optix_declarations.h" // for RT_HOSTDEVICE #include <optixu/optixu_vector_types.h> // for float3 #ifdef __cplusplus namespace optix { #endif // __cplusplus #define RT_DEFAULT_MAX 1.e27f /* Rays */ struct Ray { #ifdef __cplusplus __inline__ RT_HOSTDEVICE Ray(){} __inline__ RT_HOSTDEVICE Ray( const Ray &r) :origin(r.origin),direction(r.direction),ray_type(r.ray_type),tmin(r.tmin),tmax(r.tmax){} __inline__ RT_HOSTDEVICE Ray( float3 origin_, float3 direction_, unsigned int ray_type_, float tmin_, float tmax_ = RT_DEFAULT_MAX ) :origin(origin_),direction(direction_),ray_type(ray_type_),tmin(tmin_),tmax(tmax_){} #endif // __cplusplus float3 origin; float3 direction; unsigned int ray_type; float tmin; float tmax; }; __inline__ RT_HOSTDEVICE Ray make_Ray( float3 origin, float3 direction, unsigned int ray_type, float tmin, float tmax ) { Ray ray; ray.origin = origin; ray.direction = direction; ray.ray_type = ray_type; ray.tmin = tmin; ray.tmax = tmax; return ray; } #ifdef __cplusplus } // namespace #endif // __cplusplus #endif /* __optix_optix_datatypes_h__ */
[ [ [ 1, 76 ] ] ]
533eb1b4d4ed44164db8acc2e590cf5b8e7aa219
acf0e8a6d8589532d5585b28ec61b44b722bf213
/new_gp_daemon/template_utils.cpp
c217a88aeaa61b701cfaf7341c03e3faafadfaa8
[]
no_license
mchouza/ngpd
0f0e987a95db874b3cde4146364bf1d69cf677cb
5cca5726910bfc97844689f1f40c94b27e0fb9f9
refs/heads/master
2016-09-06T02:09:32.007855
2008-04-06T14:17:55
2008-04-06T14:17:55
35,064,755
0
0
null
null
null
null
ISO-8859-3
C++
false
false
3,369
cpp
// // Copyright (c) 2008, Mariano M. Chouza // 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. // // * The names of the contributors may not be used to endorse or promote // products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // //============================================================================= // template_utils.cpp //----------------------------------------------------------------------------- // Creado por Mariano M. Chouza | Empezado el 1 de abril de 2008 //============================================================================= #include "template_utils.h" #include <port.h> // El orden importa, debe ser anterior a 'template.h' #include <google/template.h> namespace Utils { namespace Template { // FIXME: Usar strings predefinidas!!! void fillHeader(google::TemplateDictionary& dict, const std::string& pageTitle, const std::string& scriptSrc) { using google::TemplateDictionary; TemplateDictionary* pHeaderDict = dict.AddIncludeDictionary("HEADER"); pHeaderDict->SetFilename("header.tpl"); pHeaderDict->SetValue("TITLE", pageTitle); // Si me indican que va con un script, lo agrego if (!scriptSrc.empty()) { // Agrego el valor y muestro la sección pHeaderDict->SetValueAndShowSection("SCRIPT_SRC", scriptSrc, "SCRIPT_SEC"); } } void fillPageHeader(google::TemplateDictionary& dict) { using google::TemplateDictionary; TemplateDictionary* pPageHeaderDict = dict.AddIncludeDictionary("PAGE_HEADER"); pPageHeaderDict->SetFilename("page_header.tpl"); } void fillMenu(google::TemplateDictionary& dict) { using google::TemplateDictionary; TemplateDictionary* pMenuDict = dict.AddIncludeDictionary("MENU"); pMenuDict->SetFilename("menu.tpl"); } void fillFooter(google::TemplateDictionary& dict) { using google::TemplateDictionary; TemplateDictionary* pFooterDict = dict.AddIncludeDictionary("FOOTER"); pFooterDict->SetFilename("footer.tpl"); } }} // Cierro los namespaces
[ "mchouza@b858013c-4649-0410-a850-dde43e08a396" ]
[ [ [ 1, 89 ] ] ]
4374537b4aaab10eaaf51d83863ffe81e9ad3e6c
1eb441701fc977785b13ea70bc590234f4a45705
/nukak3d/include/nkInteractorStyleEndoCamera.h
8d9efe3c2efadf0a6aab621dbc34485e6953028f
[]
no_license
svn2github/Nukak3D
942947dc37c56fc54245bbc489e61923c7623933
ec461c40431c6f2a04d112b265e184d260f929b8
refs/heads/master
2021-01-10T03:13:54.715360
2011-01-18T22:16:52
2011-01-18T22:16:52
47,416,318
1
2
null
null
null
null
ISO-8859-2
C++
false
false
3,801
h
/** * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * The Original Code is Copyright (C) 2007-2010 by Bioingenium Research Group. * Bogota - Colombia * All rights reserved. * * Author(s): Alexander Pinzón Fernández. * * ***** END GPL LICENSE BLOCK ***** */ /** * @file nkInteractorStyleEndoCamera.h * @brief Class for Endoscopy Simulator. * @details Implement all functions for Endoscopy Simulator. * @author Byron Pérez * @version 0.1 * @date 01/07/2008 03:15 p.m. */ #ifndef __nkInteractorStyleEndoCamera_h #define __nkInteractorStyleEndoCamera_h #include "vtkInteractorStyle.h" #include "vtkAbstractPropPicker.h" #include "vtkOutputWindow.h" #include "vtkCamera.h" #include "vtkCommand.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #define mensajes 1 #define VTKIS_ROTENDO 10 //class VTK_RENDERING_EXPORT nkInteractorStyleEndoCamera : public vtkInteractorStyle class nkInteractorStyleEndoCamera : public vtkInteractorStyle { public: static nkInteractorStyleEndoCamera *New(); vtkTypeRevisionMacro(nkInteractorStyleEndoCamera,vtkInteractorStyle); void PrintSelf(ostream& os, vtkIndent indent); vtkSetMacro(RestoreUpVector,int); vtkGetMacro(RestoreUpVector,int); vtkBooleanMacro(RestoreUpVector,int); // Specify "up" (by default {0,0,1} but can be changed) vtkGetVectorMacro(DefaultUpVector,double,3); vtkSetVectorMacro(DefaultUpVector,double,3); // Description: // Event bindings controlling the effects of pressing mouse buttons // or moving the mouse. virtual void OnMouseMove(); virtual void OnLeftButtonDown(); virtual void OnLeftButtonUp(); virtual void OnMiddleButtonDown(); virtual void OnMiddleButtonUp(); virtual void OnRightButtonDown(); virtual void OnRightButtonUp(); virtual void OnMouseWheelForward(); virtual void OnMouseWheelBackward(); // These methods for the different interactions in different modes // are overridden in subclasses to perform the correct motion. Since // they are called by OnTimer, they do not have mouse coord parameters // (use interactor's GetEventPosition and GetLastEventPosition) virtual void RotateEndo(); virtual void Rotate(); virtual void Spin(); virtual void Pan(); virtual void Dolly(); protected: nkInteractorStyleEndoCamera(); ~nkInteractorStyleEndoCamera(); double MotionFactor; int RestoreUpVector; double DefaultUpVector[3]; virtual void Dolly(double factor); virtual void MotionAlongVector(double vector[3], double amount, vtkCamera* cam); virtual void FinishCamera(vtkCamera* cam); void StartRotEndo(); void EndRotEndo(); //virtual void StartForwardFly(); //virtual void EndForwardFly(); private: nkInteractorStyleEndoCamera(const nkInteractorStyleEndoCamera&); // Not implemented. void operator=(const nkInteractorStyleEndoCamera&); // Not implemented. }; #endif
[ "apinzonf@4b68e429-1748-0410-913f-c2fc311d3372" ]
[ [ [ 1, 115 ] ] ]
2c570c18b08e4eca117c91d415f8958f739cef45
7f30cb109e574560873a5eb8bb398c027f85eeee
/src/appWxVtkInteractor.h
a1ed47c8f67801b33b4e56f85c31993eeafa41ac
[]
no_license
svn2github/MITO
e8fd0e0b6eebf26f2382f62660c06726419a9043
71d1269d7666151df52d6b5a98765676d992349a
refs/heads/master
2021-01-10T03:13:55.083371
2011-10-14T15:40:14
2011-10-14T15:40:14
47,415,786
1
0
null
null
null
null
ISO-8859-1
C++
false
false
20,452
h
/** * \file appWxVtkInteractor.h * \brief File per l'interazione dell'utente con la GUI * \author ICAR-CNR Napoli */ #ifndef _appWxVtkInteractor_h_ #define _appWxVtkInteractor_h_ #include "colorTransferTable.h" #include "roiManager.h" #include "segmentationManager.h" #include "viewerHandler.h" #include "wxVTKRenderWindowInteractor.h" #include <vtkColorTransferFunction.h> #include "wxWiimoteEvent.h" #include "wxWiiManager.h" //#include "wxVocalDecoder.h" #include "vtkCellLocator.h" #include "vtkDiskSource.h" #include "vtkPolyDataMapper2D.h" #include "vtkActor2D.h" #include "vtkTextActor.h" #include "vtkProperty2D.h" #include "vtkTextProperty.h" /** * \class appWxVtkInteractor * \brief Classe per l'interazione dell'utente con la GUI * * Questa classe deriva da wxVTKRenderWindowInteractor e gestisce * l'nterazione dell'utente con la GUI sia per le funzionalità * 2D (come per la ROI) che per quelle 3D */ class appWxVtkInteractor : public wxVTKRenderWindowInteractor { private: /** * \var wxWindow* _parent * \brief Finestra padre */ wxWindow* _parent; /** * \var wxPoint _actualPoint * \brief Memorizza l'ultima posizione del mouse dopo un click */ wxPoint _actualPoint; /** * \var wxTimer *m_focusTimer * \brief Timer per temporizzare il focus */ //wxTimer *m_focusTimer; /** * \var roiManager* _roiManager * \brief Gestore delle funzionalità per la ROI */ roiManager* _roiManager; /** * \var segmentationManager* _segmentationManager * \brief Gestore delle funzionalità per la segmentazione */ segmentationManager* _segmentationManager; /** * \var viewerHandler* _viewerHandler * \brief Gestore dei visualizzatori */ viewerHandler* _viewerHandler; /** * \var short _3dTechnique * \brief indica la tecnica utilizzata per la creazione del modello 3D */ short _3dTechnique; /** * \var short _interactionType * \brief Modalità di interazione */ short _interactionType; /** * \var int _clut * \brief Indica il tipo di CLUT da applicare al volume */ int _clut; /** * \var long _wl * \brief Valore del window level */ long _wl; /** * \var long _ww * \brief Valore del window width */ long _ww; /** * \var bool _wlWwModified * \brief Indica se sono stati modificati i valori di window level o window width */ bool _wlWwModified; /** * \var int _lastMousePosition[2] * \brief posizione precedente (x,y) del mouse */ int _lastMousePosition[2]; /** * \var bool _clockwise * \brief indicativa del verso di rotazione */ bool _clockwise; /** * \var bool _3DCursorCanMove * \brief indica se il cursore 3D può muoversi */ bool _3DCursorCanMove; /** * \var bool _3DCursorCanMove * \brief indica se il cursore 3D è abilitato */ bool _3DCursorEnabled; public: /** Costruttore con parametri GUI padre, identificativo della finestra e gestore dei visualizzatori */ appWxVtkInteractor(wxWindow* parent, wxWindowID id, viewerHandler* vHandler); /** Distruttore */ ~appWxVtkInteractor(); // Da dichiarare virtual nella classe padre /** * \fn void OnMouseWheel(wxMouseEvent &event) * \brief Invocato se si utilizza la rotella del mouse * \param event Evento generato dal mouse */ void OnMouseWheel(wxMouseEvent &event); /** * \fn void OnButtonDown(wxMouseEvent &event) * \brief Invocato da un click del mouse * \param event Evento generato dal mouse */ void OnButtonDown(wxMouseEvent &event); /** * \fn void OnButtonUp(wxMouseEvent &event) * \brief Invocato dopo il rilascio di un bottone del mouse * \param event Evento generato dal mouse */ void OnButtonUp(wxMouseEvent &event); /** * \fn void OnKeyDown(wxKeyEvent &event) * \brief Invocato dopo aver premuto un tasto * \param event Evento generato dalla tastiera */ void OnKeyDown(wxKeyEvent &event); /** * \fn void OnMotion(wxMouseEvent &event) * \brief Invocato dopo aver modificato la posizione del puntatore del mouse * \param event Evento generato dal mouse */ void OnMotion(wxMouseEvent &event); /** * \fn void OnEnterWindow(wxMouseEvent &event) * \brief Invocato quando il puntatore del mouse entra nella finestra del viewer * \param event Evento generato dal mouse */ void OnEnterWindow(wxMouseEvent &event); /** * \fn void OnLeaveWindow(wxMouseEvent &event) * \brief Invocato quando il puntatore del mouse esce dalla finestra del viewer * \param event Evento generato dal mouse */ void OnLeaveWindow(wxMouseEvent &event); //-----------------------------------------------Wii--------------------------------------------------------------------------------------------------- private: // numero di rendering al secondo int renderingRate; // PRISM // void prismStyle1DFilter(int & lastVelocityTime, float interval, float & invCDRatio, float newX, float & oldX); void prismStyle1DFilter(float newPosition, float & oldPosition, float & invCDRatio, wxWiiManager::Wiimote* thisWii); // void prismStyle2DFilter(int & lastVelocityTime, float interval, float & invCDRatio, float newX, float & oldX, float newY, float & oldY); bool prismStyle2DFilter(float newX, float & oldX, float newY, float & oldY, float & invCDRatio, wxWiiManager::Wiimote* thisWii); // fine PRISM /** * \var wxWiiManager* WiiManager * \brief puntatore al Manager dei Wiimote collegati. */ wxWiiManager* WiiManager; double camPosition[3]; double camViewUp[3]; // ultimo tempo di render __int64 _lastRenderTime; // frequenza di clock __int64 _clockFrequency; // per il log - lista che poi viene scritta sul file di log vector<string> list; // per il log - frequenza di clock __int64 _lastUpdatedTime; // per il log - generico istante di tempo __int64 _updatedTime; // per il log - istante iniziale dell'interazione __int64 _initialTime; /** * \bool enabledWiiX; * \brief Utilizzarto per abilitare la rotazione lungo un asse per volta. */ bool enabled_angle_Rotation; /** * \bool enabledWiiY; * \brief Utilizzarto per abilitare la rotazione lungo un asse per volta. */ bool enabled_ryf_Rotation; /** * \bool enabledWiiIR; * \brief Utilizzarto per abilitare la rotazione lungo un asse per volta. */ bool enabled_rxf_Rotation; /** * \vtkActor2D* interactionSignal * \brief Attore 2D rappresentante il segnale di interazione. */ vtkActor2D* interactionSignal; /** * \vtkTextActor* interactionSignalText * \brief TextActor utilizzato per indicare il tipo di interazione in atto. */ vtkTextActor* interactionSignalText; /** * \vtkActor2D* rxfRotationAxis * \brief Attore 2D rappresentante l'asse di rotazione rxf. */ vtkAxisActor2D* rxfRotationAxis; /** * \vtkActor2D* ryfRotationAxis * \brief Attore 2D rappresentante l'asse di rotazione ryf. */ vtkAxisActor2D* ryfRotationAxis; /** * \vtkActor2D* angleRotationAxis * \brief Mapper associato all' Actor2D rappresentante l'asse di rotazione angle. */ vtkActor2D* angleRotationAxis; /** * \vtkActor2D* degreeRotationIndicator * \brief Actor2D associato all' indicatore rappresentante i margini di rotazione imprimibili. */ vtkActor2D* degreeRotationIndicator; /** * \fn void showInteractionSignal(int signalColor, char* text) * \brief Mostra l'indicatore del tipo di interazione in atto. * \param signalColor Indica il colore che deve avere l'indicatore. * \ text Carattere che deve essere visualizzato dall'indicatore. */ void showInteractionSignal(int signalColor, char* text); /** * \fn void hideInteractionSignal() * \brief Nasconde l'indicatore del tipo di interazione in atto. */ void hideInteractionSignal(); /** * \fn showRotationIndicator(int rotationType, int signalColor = 0, float p0 = 0, float p = 0) * \brief Mostra l'indicatore dell'oggetto in movimento lungo l'asse di rotazione scelto. * \param rotationType Indica l'asse di rotazione e quindi il tipo di movimento da effettuare. * \ signalColor Indica il colore che deve avere l'indicatore in movimento. * \ p0 Posizione iniziale dell' oggetto 3D. * \ p Posizione attuale dell' oggetto 3D. */ void showRotationIndicator(int rotationType, int signalColor = 0, float p0 = 0, float p = 0); void showRotationIndicator(int rotationType, float p = 0, int signalColor = 0); /** * \fn void hideRotationIndicator() * \brief Nasconde l'indicatore dell'oggetto in movimento lungo l'asse di rotazione scelto. */ void hideRotationIndicator(); /** * \bool InteractionSignalsAdded * \brief Indica se gli indicatori visivi delle interazioni son stati aggiunti nella scena. */ bool InteractionSignalsAdded; /** * \bool isRenderingNeeded(int frameRate) * \brief Indica se è necessario effettuare un render in base al frame rate in input * \param frameRate Frame rate */ bool isRenderingNeeded(int frameRate); /** * \void updateLastRenderTime() * \brief Aggiorna all'attuale tempo di sistema, il valore del tempo a cui è stato effettuato l'ultimo render * \param frameRate Frame rate */ //void updateLastRenderTime(double delay=0); void updateLastRenderTime(); public: float _minDISP; float _maxDISP; /** * \var int idWiiEnabled * \brief Indica l'id del Wiimote abilitato ad interagire col sistema. * \Porre a -1 per abilitare tutti i Wiimote */ int idWiiEnabled; bool _isSceneRotatingIR_1; /** * \fn wxWiiManager* getWiiManager(wxVtkViewer3d* viewer3d) * \brief Ritorna il puntatore al WiiManager, creando il manager se non esiste. * \param viewer3d Puntatore al viewer 3d della scena, da passare al costruttore del WiiManager. */ wxWiiManager* getWiiManager(wxVtkViewer3d* viewer3d); /** * \fn void closeWiiManager() * \brief Distrugge il WiiManager. */ void closeWiiManager(); /** * \var bool WiiManagerStarted * \brief Vale true se il Manager dei Wii è operativo. */ bool WiiManagerStarted; /** * \fn bool closeWiiAbility() * \brief Se nessuno sta manipolando, chiude se occorre l'interazione vtkPointing */ bool closeWiiAbility(); /** * \fn void initInteractionSignals() * \brief Inizializza ed aggiunge alla scena i segnali visivi relativi all' interazione. */ void initInteractionSignals(); /** * \fn void removeInteractionSignals() * \brief Rimuove dalla scena i segnali visivi relativi all' interazione. */ void removeInteractionSignals(); /** * \fn void onWiiMotionIR(wxWiimoteEvent &event) * \brief Invocato periodicamente dal Wiimote * \param event Evento generato dal Wiimote */ void onWiiMotionIR ( wxWiimoteEvent & event ); /** * \fn void onWiiADown(wxWiimoteEvent &event) * \brief Invocato dopo aver premuto il pulsante A del Wiimote * \param event Evento generato dal Wiimote */ void onWiiADown ( wxWiimoteEvent & event ); /** * \fn void onWiiAUp(wxWiimoteEvent &event) * \brief Invocato dopo aver rilasciato il pulsante A del Wiimote * \param event Evento generato dal Wiimote */ void onWiiAUp ( wxWiimoteEvent & event ); /** * \fn void onWiiBDown(wxWiimoteEvent &event) * \brief Invocato dopo aver premuto il pulsante B del Wiimote * \param event Evento generato dal Wiimote */ void onWiiBDown ( wxWiimoteEvent & event ); /** * \fn void onWiiBUp(wxWiimoteEvent &event) * \brief Invocato dopo aver rilasciato il pulsante B del Wiimote * \param event Evento generato dal Wiimote */ void onWiiBUp ( wxWiimoteEvent & event ); /** * \fn void onWiiMinusDown(wxWiimoteEvent &event) * \brief Invocato dopo aver premuto il pulsante Minus del Wiimote * \param event Evento generato dal Wiimote */ void onWiiMinusDown ( wxWiimoteEvent & event ); /** * \fn void onWiiMinusUp(wxWiimoteEvent &event) * \brief Invocato dopo aver rilasciato il pulsante Minus del Wiimote * \param event Evento generato dal Wiimote */ void onWiiMinusUp ( wxWiimoteEvent & event ); /** * \fn void onWiiHomeDown(wxWiimoteEvent &event) * \brief Invocato dopo aver premuto il pulsante Home del Wiimote * \param event Evento generato dal Wiimote */ void onWiiHomeDown ( wxWiimoteEvent & event ); /** * \fn void onWiiHomeUp(wxWiimoteEvent &event) * \brief Invocato dopo aver rilasciato il pulsante Home del Wiimote * \param event Evento generato dal Wiimote */ void onWiiHomeUp ( wxWiimoteEvent & event ); /** * \fn void onWiiPlusDown(wxWiimoteEvent &event) * \brief Invocato dopo aver premuto il pulsante Plus del Wiimote * \param event Evento generato dal Wiimote */ void onWiiPlusDown ( wxWiimoteEvent & event ); /** * \fn void onWiiPlusUp(wxWiimoteEvent &event) * \brief Invocato dopo aver rilasciato il pulsante Plus del Wiimote * \param event Evento generato dal Wiimote */ void onWiiPlusUp ( wxWiimoteEvent & event ); /** * \fn void onWiiOneDown(wxWiimoteEvent &event) * \brief Invocato dopo aver premuto il pulsante One del Wiimote * \param event Evento generato dal Wiimote */ void onWiiOneDown ( wxWiimoteEvent & event ); /** * \fn void onWiiOneUp(wxWiimoteEvent &event) * \brief Invocato dopo aver rilasciato il pulsante One del Wiimote * \param event Evento generato dal Wiimote */ void onWiiOneUp ( wxWiimoteEvent & event ); /** * \fn void onWiiTwoDown(wxWiimoteEvent &event) * \brief Invocato dopo aver premuto il pulsante Two del Wiimote * \param event Evento generato dal Wiimote */ void onWiiTwoDown ( wxWiimoteEvent & event ); /** * \fn void onWiiTwoUp(wxWiimoteEvent &event) * \brief Invocato dopo aver rilasciato il pulsante Two del Wiimote * \param event Evento generato dal Wiimote */ void onWiiTwoUp ( wxWiimoteEvent & event ); /** * \fn void onWiiCrossDown(wxWiimoteEvent &event) * \brief Invocato dopo aver premuto la Croce del Wiimote * \param event Evento generato dal Wiimote */ void onWiiCrossDown ( wxWiimoteEvent & event ); /** * \fn void onWiiCrossUp(wxWiimoteEvent &event) * \brief Invocato dopo aver rilasciato la Croce del Wiimote * \param event Evento generato dal Wiimote */ void onWiiCrossUp ( wxWiimoteEvent & event ); //------------------------------------------------------------------------------------------------------------------ /** * \fn void OnMotion(wxMouseEvent &event) * \brief Invocato dopo aver modificato le dimensione della finestra * \param event Evento generato dal ridimensionamento della finestra */ void OnSize(wxSizeEvent &event); //void OnFocusTimer(wxTimerEvent& event); //void OnLeave(wxMouseEvent &event); /** * \fn short getInteractionType() * \brief Restituisce il valore della variabile _interactionType * \return Valore della variabile _interactionType */ inline short getInteractionType() { return _interactionType; } /** * \fn void setInteractionType(short interactionType) * \brief Assegna l'interactionType * \param interactionType Modalità di interazione da assegnare a _interactionType */ inline void setInteractionType(short interactionType) { _interactionType = interactionType; } /** * \fn void set3dTechnique(short technique) * \brief Assegna la tecnica 3D * \param technique tecnica utilizzata per la creazione della rappresentazione 3d */ inline void set3dTechnique(short technique) { _3dTechnique = technique; } /** * \fn short get3dTechnique() * \brief Ritorna la 3dTechnique * \return Valore della variabile 3dTechnique */ inline short get3dTechnique() { return _3dTechnique; } /** * \fn void setWlWw(double wl, double ww) * \brief Assegna window level e window width * \param wl Window level * \param ww Window width */ inline void setWlWw(double wl, double ww) { _wl = wl; _ww = ww; } /** * \fn void getWl() * \brief Restituisce il window level */ inline long getWl() { return _wl; } /** * \fn void getWw() * \brief Restituisce il window width */ inline long getWw() { return _ww; } /** * \fn bool getWlWwModified() * \brief Restituisce il valore della variabile _wlWwModified * \reutrn Valore della variabile _wlWwModified */ inline bool getWlWwModified() { return _wlWwModified; } /** * \fn void setWlWwModified() * \brief Assegna il valore alla variabile _wlWwModified * \param wlWwModified Valore da assegnare */ inline void setWlWwModified(bool wlWwModified) { _wlWwModified = wlWwModified; } /** * \fn short getInteractionType() * \brief Restituisce il gestore delle funzionalità per la ROI * \return Gestore ROI */ inline roiManager* getRoiManager(){ return _roiManager; } /** * \fn short getInteractionType() * \brief Restituisce il gestore delle funzionalità per la segmentazione * \return Gestore segmentazione */ inline segmentationManager* getSegmentationManager(){ return _segmentationManager; } /** * \fn void setSegmentationManager(segmentationManager* segmentationMngr) * \brief Assegna il gestore delle funzionalità per la segmentazione * \param segmentationMngr Gestore delle funzionalità per la segmentazione */ inline void setSegmentationManager(segmentationManager* segmentationMngr) { _segmentationManager = segmentationMngr; } /** * \fn void setCLUT(int clut) * \brief Indica il tipo di CLUT * \param clut Tipo di CLUT */ inline void setCLUT(int clut) { _clut = clut; } /** * \fn void 3DcursorOn() * \brief Puntatore 3D attivo */ void set3DcursorOn() { _3DCursorEnabled = true; } /** * \fn void 3DcursorOff() * \brief Puntatore 2D attivo */ void set3DcursorOff() { _3DCursorEnabled = false; } /** * \fn void get3DcursorMode() * \brief Ritorna la modalità di puntamento */ bool get3DcursorMode() { return _3DCursorEnabled; } void set3DcursorCanMove(bool move) { _3DCursorCanMove = move; } /** * \fn void dummyMethod() * \brief simula un click del tasto sinistro del mouse */ void dummyMethod(); /** * \fn void dummyMethod() * \brief simula un click del tasto destro del mouse */ void dummyMethodRight(); DECLARE_EVENT_TABLE(); }; /** * \brief Tipo enumerativo che rappresenta i differenti device di interazione utilizzabili */ enum interactionDevice { MouseDevice, WiimoteDevice }; /** * \brief Tipo enumerativo che rappresenta le differenti modalità con cui un utente può interagire con un finestra */ enum { all2d = 0, windowLevel2d, move2d, zoom2d, rotate2d, animate2d, length2d, angle2d, rectangle2d, polygon2d, pencil2d, connectedThreshold2d, neighborhoodConnected2d, confidenceConnected2d, windowLevel3d, move3d, dolly3dVR, dolly3dSR, zoom3dSR, zoom3dVR, rotate3d, rotateAround3d, rotateAround3dSR, voi3dVR, voi3dVRwii, voi3dSR, wii, wiiSR }; /** * \brief Tipo enumerativo che rappresenta il tipo di finestra 3d */ enum { Undecided = 0, VolumeRenderingMitoCinese, SurfaceRendering }; //-----------------------------------------------Wii---------------------------------------------------------------- /** * \brief Tipo enumerativo utilizzato per concedere il permesso di interazione a qualunque wiimote lo richieda * \e per rappresentare le differenti modalità con cui un wiimote può interagire nella scena 3d. */ enum { AnyWiiEnabled = -1, Waiting, SceneTranslating, SceneRotating, SceneRotatingIR, SceneRotatingIR_1, SceneRolling, CameraDollyIn, CameraDollyOut, SceneZoomingIn, SceneZoomingOut, SceneVocalAcquiring, BoxWidgetSelecting, BoxWidgetTranslating, BoxWidgetRotating, Pointing }; //------------------------------------------------------------------------------------------------------------------ #endif _appWxVtkInteractor_h_
[ "kg_dexterp37@fde90bc1-0431-4138-8110-3f8199bc04de" ]
[ [ [ 1, 771 ] ] ]
e9a95f174583cc79740c24e0aef92afe4f12e0c6
b4d726a0321649f907923cc57323942a1e45915b
/CODE/ImpED/MessageEditorDlg.h
0ab4f6d40a66f7cdc18dce6115cc9f7a72a4bbfa
[]
no_license
chief1983/Imperial-Alliance
f1aa664d91f32c9e244867aaac43fffdf42199dc
6db0102a8897deac845a8bd2a7aa2e1b25086448
refs/heads/master
2016-09-06T02:40:39.069630
2010-10-06T22:06:24
2010-10-06T22:06:24
967,775
2
0
null
null
null
null
UTF-8
C++
false
false
3,888
h
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ /* * $Logfile: /Freespace2/code/FRED2/MessageEditorDlg.h $ * $Revision: 1.2 $ * $Date: 2002/08/15 01:06:34 $ * $Author: penguin $ * * Old message editor dialog box handling code. This was designed a LONG time ago * and because so much changed, I created a new one from scratch instead. This is * only around just in case it might be useful. * * $Log: MessageEditorDlg.h,v $ * Revision 1.2 2002/08/15 01:06:34 penguin * Include filename reorg (to coordinate w/ fs2_open) * * Revision 1.1.1.1 2002/07/15 03:10:59 inquisitor * Initial FRED2 Checking * * * 2 10/07/98 6:28p Dave * Initial checkin. Renamed all relevant stuff to be Fred2 instead of * Fred. Globalized mission and campaign file extensions. Removed Silent * Threat specific code. * * 1 10/07/98 3:01p Dave * * 1 10/07/98 3:00p Dave * * 11 1/07/98 5:58p Hoffoss * Combined message editor into event editor. * * 10 1/06/98 4:19p Hoffoss * Made message editor accept returns instead of closing dialog. * * 9 10/13/97 11:37a Allender * added personas to message editor in Fred * * 8 10/08/97 4:41p Hoffoss * Changed the way message editor works. Each message is updated * perminently when you switch messages (as if ok button was pressed). * * 7 7/14/97 9:55p Hoffoss * Making changes to message editor system. * * 6 7/10/97 2:32p Hoffoss * Made message editor dialog box modeless. * * 5 7/02/97 5:09p Hoffoss * Added browse buttons to message editor. * * 4 5/20/97 2:28p Hoffoss * Added message box queries for close window operation on all modal * dialog boxes. * * 3 3/11/97 2:19p Hoffoss * New message structure support for Fred. * * 2 2/17/97 5:28p Hoffoss * Checked RCS headers, added them were missing, changing description to * something better, etc where needed. * * $NoKeywords: $ */ #include "mission/missionmessage.h" ///////////////////////////////////////////////////////////////////////////// // CMessageEditorDlg dialog class CMessageEditorDlg : public CDialog { // Construction public: int find_event(); int query_modified(); void OnCancel(); int update(int num); void update_cur_message(); void OnOK(); CMessageEditorDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CMessageEditorDlg) enum { IDD = IDD_MESSAGE_EDITOR }; sexp_tree m_tree; CString m_avi_filename; CString m_wave_filename; CString m_message_text; CString m_message_name; int m_cur_msg; int m_priority; int m_sender; int m_persona; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMessageEditorDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: int m_event_num; // event index if existing event is being used for formula int modified; // Generated message map functions //{{AFX_MSG(CMessageEditorDlg) virtual BOOL OnInitDialog(); afx_msg void OnSelchangeMessageList(); afx_msg void OnUpdateName(); afx_msg void OnDelete(); afx_msg void OnNew(); afx_msg void OnClose(); afx_msg void OnBrowseAvi(); afx_msg void OnBrowseWave(); afx_msg void OnRclickTree(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnBeginlabeleditTree(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnEndlabeleditTree(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnOk(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; extern CMessageEditorDlg *Message_editor_dlg;
[ [ [ 1, 135 ] ] ]
f1228f449690acbe55fd5857702fb00e94f891ff
701f9ab221639b56c28417ee6f6ee984acb24142
/Src/Force Engine/Importer/Importer.cpp
7c18c1c53d2c02d216bffbb6e13b87e576ee843c
[]
no_license
nlelouche/desprog1
2397130e427b4ada83721ecbb1a131682bc73187
71c7839675698e74ca43dd26c4af752e309dccb6
refs/heads/master
2021-01-22T06:33:14.083467
2010-02-26T16:18:39
2010-02-26T16:18:39
32,653,851
0
0
null
null
null
null
UTF-8
C++
false
false
4,186
cpp
//-------------------------------------------------------------------// //* *// //* Importer.cpp - Created 04/07/2008 *// //* PitBull Engine V0.1 *// //* By CalaveraX *// //-------------------------------------------------------------------// //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include <fstream> #include "Importer.h" //--------------------------------------------------------------------------- bool Importer::ImportSprite(const char *pszName, Sprite &rkSprite,Render *pkRender){ // Creamos el MainNode que usaremos para leer los Encabezados XML XMLNode rkNode = XMLNode::openFileHelper(pszName,"PMML"); // Creamos el node desde Sprite XMLNode rkSpriteNode = rkNode.getChildNode("SPRITE"); // load sprite attributes const char* pszFile = rkSpriteNode.getAttribute("File"); const char* pszColorkeyR = rkSpriteNode.getAttribute("ColorkeyR"); const char* pszColorkeyG = rkSpriteNode.getAttribute("ColorkeyG"); const char* pszColorkeyB = rkSpriteNode.getAttribute("ColorkeyB"); const char* pszTexPosX = rkSpriteNode.getAttribute("TexPosX"); const char* pszTexPosY = rkSpriteNode.getAttribute("TexPosY"); const char* pszWidth = rkSpriteNode.getAttribute("Width"); const char* pszHeight = rkSpriteNode.getAttribute("Height"); // Creamos una nueva Textura desde el archivo pszFile Texture::Ptr m_pkTexture(new Texture(pszFile)); // Indicamos al render cargar la textura pkRender->loadTexture(m_pkTexture, D3DCOLOR_XRGB( atoi(pszColorkeyR), atoi(pszColorkeyG), atoi(pszColorkeyB)) ); // Seteamos las propiedades del Sprite rkSprite.SetTexture(m_pkTexture); rkSprite.SetDim(float(atoi(pszWidth)),float(atoi(pszHeight))); rkSprite.SetName(pszName); rkSprite.SetPos(0,0); rkSprite.setTextureArea(atoi(pszTexPosX), atoi(pszTexPosY), atoi(pszWidth), atoi(pszHeight)); return true; } //--------------------------------------------------------------------------- bool Importer::ImportSpriteAnimation (const char *pszName, Sprite &rkSprite) { // Creamos el MainNode que usaremos para leer los Encabezados XML XMLNode rkNode = XMLNode::openFileHelper(pszName,"PMML"); // Creamos el nodo desde SPRITE_ANIMATION XMLNode rkAnimationNode = rkNode.getChildNode("SPRITE_ANIMATION"); // Get total of Animations int iTotalAnims = rkNode.nChildNode("SPRITE_ANIMATION"); // For Each Animation: int iIterator = 0; for(int i=0; i<iTotalAnims; i++){ // Create the New AnimationInfo AnimationInfo::Ptr pkAnimInfo = AnimationInfo::Ptr( new AnimationInfo() ); // get animation attibutes const char* pszTime = rkAnimationNode.getAttribute("Time"); // convert animation attibutes float fTime = (float)(strtod(pszTime,NULL)); pkAnimInfo->setLength(fTime); // Get Animation Name const char* pszName = rkAnimationNode.getAttribute("Name"); // load frames int iTotalFrames = rkAnimationNode.nChildNode("FRAME"); // For each Frame int iIterator = 0; for(int i=0; i<iTotalFrames; i++){ // Creamos el Nodo a partir de FRAME XMLNode& rkFrame = rkAnimationNode.getChildNode("FRAME",&iIterator); // get frame data const char* pszTexPosX = rkFrame.getAttribute("TexPosX"); const char* pszTexPosY = rkFrame.getAttribute("TexPosY"); const char* pszWidth = rkFrame.getAttribute("Width"); const char* pszHeight = rkFrame.getAttribute("Height"); // convert frame data unsigned int uiTexPosX = atoi(pszTexPosX); unsigned int uiTexPosY = atoi(pszTexPosY); unsigned int uiWidth = atoi(pszWidth); unsigned int uiHeight = atoi(pszHeight); // Agregamos el Frame a AnimationInfo pkAnimInfo->addFrame(uiTexPosX, uiTexPosY, uiWidth, uiHeight); } //Animation *pkAnimation = new Animation(pkAnimInfo); //Agregamos AnimationInfo al Sprite rkSprite.addAnimationInfo(pszName, pkAnimInfo); } return true; } //---------------------------------------------------------------------------
[ "gersurfer@a82ef5f6-654a-0410-99b4-23d68ab79cb1" ]
[ [ [ 1, 116 ] ] ]
b29bdf6c17010908b9997b7f2a3d6de0e572687f
801e9a21fbe0f68c18857334f9b86694938f5055
/Documentacion/QextSerialPort/qextserialport/examples/qespta/QespTest.cpp
3d928b0d5e4ac9cc9493cd6addd67fb7aaf2758b
[]
no_license
vialrogo/pbx-viewer
d324cbec618fdbaee78f79a8466ebf64c54ffa34
b814668c46a2d0f85bffcfed0d06dd8e96a082b8
refs/heads/master
2016-09-05T11:57:26.787183
2010-09-16T16:34:49
2010-09-16T16:34:49
32,185,339
0
1
null
null
null
null
UTF-8
C++
false
false
3,028
cpp
/* qesptest.cpp **************************************/ #include "qesptest.h" #include <qextserialport.h> #include <QLayout> #include <QLineEdit> #include <QTextEdit> #include <QPushButton> #include <QSpinBox> QespTest::QespTest(QWidget* parent) : QWidget(parent) { //modify the port settings on your own port = new QextSerialPort("/dev/ttyUSB0"); port->setBaudRate(BAUD19200); port->setFlowControl(FLOW_OFF); port->setParity(PAR_NONE); port->setDataBits(DATA_8); port->setStopBits(STOP_1); message = new QLineEdit(this); // transmit receive QPushButton *transmitButton = new QPushButton("Transmit"); connect(transmitButton, SIGNAL(clicked()), SLOT(transmitMsg())); QPushButton *receiveButton = new QPushButton("Receive"); connect(receiveButton, SIGNAL(clicked()), SLOT(receiveMsg())); QHBoxLayout* trLayout = new QHBoxLayout; trLayout->addWidget(transmitButton); trLayout->addWidget(receiveButton); //CR LF QPushButton *CRButton = new QPushButton("CR"); connect(CRButton, SIGNAL(clicked()), SLOT(appendCR())); QPushButton *LFButton = new QPushButton("LF"); connect(LFButton, SIGNAL(clicked()), SLOT(appendLF())); QHBoxLayout *crlfLayout = new QHBoxLayout; crlfLayout->addWidget(CRButton); crlfLayout->addWidget(LFButton); //open close QPushButton *openButton = new QPushButton("Open"); connect(openButton, SIGNAL(clicked()), SLOT(openPort())); QPushButton *closeButton = new QPushButton("Close"); connect(closeButton, SIGNAL(clicked()), SLOT(closePort())); QHBoxLayout *ocLayout = new QHBoxLayout; ocLayout->addWidget(openButton); ocLayout->addWidget(closeButton); received_msg = new QTextEdit(); QVBoxLayout *myVBox = new QVBoxLayout; myVBox->addWidget(message); myVBox->addLayout(crlfLayout); myVBox->addLayout(trLayout); myVBox->addLayout(ocLayout); myVBox->addWidget(received_msg); setLayout(myVBox); qDebug("isOpen : %d", port->isOpen()); } QespTest::~QespTest() { delete port; port = NULL; } void QespTest::transmitMsg() { int i = port->write((message->text()).toAscii(), (message->text()).length()); qDebug("trasmitted : %d", i); } void QespTest::receiveMsg() { char buff[1024]; int numBytes; numBytes = port->bytesAvailable(); if(numBytes > 0) { if(numBytes > 1024) numBytes = 1024; int i = port->read(buff, numBytes); buff[i] = '\0'; QString msg = buff; received_msg->append(msg); received_msg->ensureCursorVisible(); qDebug("bytes available: %d", numBytes); qDebug("received: %d", i); } } void QespTest::appendCR() { message->insert("\x0D"); } void QespTest::appendLF() { message->insert("\x0A"); } void QespTest::closePort() { port->close(); qDebug("is open: %d", port->isOpen()); } void QespTest::openPort() { port->open(QIODevice::ReadWrite); qDebug("is open: %d", port->isOpen()); }
[ "varg04444@58e77f3c-66d3-2f76-d9f4-08142b3b8c59" ]
[ [ [ 1, 121 ] ] ]
cba0cd10b9087647e13b00b945330c19b6b823d6
3a79a741fe799d531f363834255d1ce15a520258
/artigos/arquiteturaDeJogos/programacao/animacao/math/Vector2D.h
690f6341ea42dcf03f550b953b1618b0ee158e60
[]
no_license
ViniGodoy/pontov
a8bd3485c53d5fc79312f175610a2962c420c40d
01f8f82209ba10a57d9d220d838cbf00aede4cee
refs/heads/master
2020-04-24T19:33:24.288796
2011-06-20T21:44:03
2011-06-20T21:44:03
32,488,089
0
0
null
null
null
null
IBM852
C++
false
false
3,600
h
/* VinÝcius Godoy de Mendonša */ #ifndef __VECTOR2D_H__ #define __VECTOR2D_H__ #include "MathUtil.h" namespace math { /** This class represents a 2 coordinate space mathematical vector. All operations expected for a vector, like sum, subtraction, product, cross product, dot product and normalization are provided. */ class Vector2D { private: float x; float y; public: /** Builds a NULL vector */ Vector2D(); /** Builds a vector based in it's x and y components */ Vector2D(float aX, float anY); /** Copy constructor */ Vector2D(const Vector2D& other); /** Builds a vector based in it's size (magnitude) and angle */ static Vector2D createBySizeAngle(float mag, float angle); /** Retrieves the magnitude of the vector component in X */ inline float Vector2D::getX() const { return x; } /** Returns the magnitude of the vector component in Y*/ inline float Vector2D::getY() const { return y; } /** Changes the x and y values */ Vector2D& set(float x, float y); /** Retrieves the size of this vector squared */ float getSizeSqr() const; /** Retrieves this vector magnitude */ float getSize() const; /** Changes this vector magnitude. This operation will not interfere * in the vector angulation. * Return this vector itself, after changing the magnitude. */ Vector2D& setSize(float _size); /** Returns the angle of the vector in relation to the x * axis, in a counter-clockwise rotation. That is, 90 degrees is * a vector pointing up and 0 degrees is a vector pointing right. */ float getAngle() const; /** Rotates the vector counter-clockwise. * Returns the vector itself, after the rotation. */ Vector2D& rotate(float angle); /** Normalizes this vector. * Returns the vector itself, after the normalization. */ Vector2D& normalize(); /** Assignment operator. */ Vector2D& operator = (const Vector2D& other); /** Adds this vector to another vector */ Vector2D& operator += (const Vector2D& other); /** Subtracts this vector from another vector */ Vector2D& operator -= (const Vector2D& other); /** Multiplies the magnitude of this vector to a constant */ Vector2D& operator *= (float c); /** Divides this vector magnitude by a constant*/ Vector2D& operator /= (float c); /** Negates this vector. * Same as rotating the vector in 180║ but possibly much faster. */ Vector2D operator -(void) const; Vector2D operator +(const Vector2D& other) const; Vector2D operator -(const Vector2D& other) const; Vector2D operator *(float c) const; Vector2D operator /(float c) const; bool operator ==(const Vector2D& other) const; float dot(const Vector2D& other) const; float angleBetween(const Vector2D other) const; float angleSign(const Vector2D& v) const; }; } #endif
[ "bcsanches@7ec48984-19c3-11df-a513-1fc609e2573f" ]
[ [ [ 1, 101 ] ] ]
2c1f9f4d9fb423aae8fd88ee440c096ee859ff9f
9a5db9951432056bb5cd4cf3c32362a4e17008b7
/FacesCapture/branches/FaceCompare/RemoteImaging/FaceSearchWrapper/FaceSearchWrapper.h
12c7d4e79f67747738ab60298cbcb50220bb131b
[]
no_license
miaozhendaoren/appcollection
65b0ede264e74e60b68ca74cf70fb24222543278
f8b85af93f787fa897af90e8361569a36ff65d35
refs/heads/master
2021-05-30T19:27:21.142158
2011-06-27T03:49:22
2011-06-27T03:49:22
null
0
0
null
null
null
null
GB18030
C++
false
false
5,891
h
// FaceSearchWrapper.h #pragma once #include "../../OutPut/FaceSelect.h" using namespace System; using namespace System::Runtime::InteropServices; namespace FaceSearchWrapper { public ref class FaceSearch { // TODO: Add your methods for this class here. public: FaceSearch() { this->pFaceSearch = new CFaceSelect(); } ~FaceSearch() { delete pFaceSearch; } //Michael Add -- 设置类变量的接口 void SetROI( int x, int y, int width, int height ) { pFaceSearch->SetROI(x, y, width, height); } void SetFaceParas( int iMinFace, double dFaceChangeRatio) { pFaceSearch->SetFaceParas(iMinFace, dFaceChangeRatio); } void SetDwSmpRatio( double dRatio ) { pFaceSearch->SetDwSmpRatio(dRatio); } void SetOutputDir( const char* dir ) { pFaceSearch->SetOutputDir(dir); } //SetExRatio : 设置输出的图片应在人脸的四个方向扩展多少比例 //如果人脸框大小保持不变,4个值都应该为0.0f void SetExRatio( double topExRatio, double bottomExRatio, double leftExRatio, double rightExRatio ) { pFaceSearch->SetExRatio(topExRatio, bottomExRatio, leftExRatio, rightExRatio); } void SetLightMode(int iMode) { pFaceSearch->SetLightMode(iMode); } void AddInFrame(ImageProcess::Frame^ frame) { Frame frm; frm.cameraID = frame->cameraID; frm.image = (::IplImage *) frame->image->CvPtr.ToPointer(); frm.searchRect.x = frame->searchRect.X; frm.searchRect.y = frame->searchRect.Y; frm.searchRect.width = frame->searchRect.Width; frm.searchRect.height = frame->searchRect.Height; frm.timeStamp = frame->timeStamp; pFaceSearch->AddInFrame(frm); } array<ImageProcess::Target^>^ SearchFacesFastMode(ImageProcess::Frame^ frame) { AddInFrame(frame); return SearchFaces(); } array<ImageProcess::Target^>^ SearchFaces() { ::Target *pFacesFound = NULL; int faceGroupCount = pFaceSearch->SearchFaces(&pFacesFound); System::Diagnostics::Debug::WriteLine("after search in wrapper"); array<ImageProcess::Target^>^ mtArray = gcnew array<ImageProcess::Target^>(faceGroupCount); for (int i=0; i<faceGroupCount; ++i) { mtArray[i] = gcnew ImageProcess::Target; mtArray[i]->BaseFrame = gcnew ImageProcess::Frame; Frame unmanagedBaseFrame = pFacesFound[i].BaseFrame; mtArray[i]->BaseFrame->cameraID = pFacesFound[i].BaseFrame.cameraID; mtArray[i]->BaseFrame->image = gcnew OpenCvSharp::IplImage( (IntPtr) unmanagedBaseFrame.image ); mtArray[i]->BaseFrame->image->IsEnabledDispose = false; mtArray[i]->BaseFrame->searchRect.X = unmanagedBaseFrame.searchRect.x; mtArray[i]->BaseFrame->searchRect.Y = unmanagedBaseFrame.searchRect.y; mtArray[i]->BaseFrame->searchRect.Width = unmanagedBaseFrame.searchRect.width; mtArray[i]->BaseFrame->searchRect.Height = unmanagedBaseFrame.searchRect.height; mtArray[i]->BaseFrame->timeStamp = unmanagedBaseFrame.timeStamp; int facesCount = pFacesFound[i].FaceCount; mtArray[i]->Faces = gcnew array<OpenCvSharp::IplImage^>(facesCount); mtArray[i]->FacesRects = gcnew array<OpenCvSharp::CvRect>(facesCount); mtArray[i]->FacesRectsForCompare = gcnew array<OpenCvSharp::CvRect>(facesCount); for (int j=0; j<facesCount; ++j) { mtArray[i]->Faces[j] = gcnew OpenCvSharp::IplImage( (IntPtr) pFacesFound[i].FaceData[j] ); mtArray[i]->Faces[j]->IsEnabledDispose = false; mtArray[i]->FacesRects[j] = UnmanagedRectToManaged(pFacesFound[i].FaceRects[j]); mtArray[i]->FacesRectsForCompare[j] = UnmanagedRectToManaged(pFacesFound[i].FaceOrgRects[j]); } } return mtArray; } OpenCvSharp::IplImage^ NormalizeImage(OpenCvSharp::IplImage^ imgIn, OpenCvSharp::CvRect roi) { IplImage* unmanagedIn = (IplImage *) imgIn->CvPtr.ToPointer(); IplImage* unmanagedNormalized = NULL; ::CvRect UnmanagedRect = ManagedRectToUnmanaged(roi); pFaceSearch->FaceImagePreprocess(unmanagedIn, unmanagedNormalized, UnmanagedRect); assert(unmanagedNormalized != NULL); OpenCvSharp::IplImage^ normalized = gcnew OpenCvSharp::IplImage((IntPtr) unmanagedNormalized); normalized->IsEnabledDispose = false; return normalized; } array<OpenCvSharp::IplImage^>^ NormalizeImageForTraining(OpenCvSharp::IplImage^ imgIn, OpenCvSharp::CvRect roi) { ::IplImage *pUnmanagedIn = (::IplImage *) imgIn->CvPtr.ToPointer(); ImageArray trainedImages; ZeroMemory(&trainedImages, sizeof(trainedImages)); ::CvRect unmanagedRect = ManagedRectToUnmanaged(roi); pFaceSearch->FaceImagePreprocess_ForTrain(pUnmanagedIn, trainedImages, unmanagedRect); array<OpenCvSharp::IplImage^>^ returnArray = gcnew array<OpenCvSharp::IplImage^>(trainedImages.nImageCount); for (int i=0; i<trainedImages.nImageCount; ++i) { assert(trainedImages.imageArr[i] != NULL); returnArray[i] = gcnew OpenCvSharp::IplImage((IntPtr) trainedImages.imageArr[i]); } pFaceSearch->ReleaseImageArray(trainedImages); return returnArray; } private: ::CvRect ManagedRectToUnmanaged(OpenCvSharp::CvRect^ managedRect) { CvRect unmanagedRect; unmanagedRect.x = managedRect->X; unmanagedRect.y = managedRect->Y; unmanagedRect.width = managedRect->Width; unmanagedRect.height = managedRect->Height; return unmanagedRect; } OpenCvSharp::CvRect UnmanagedRectToManaged(const ::CvRect& unmanaged) { OpenCvSharp::CvRect managed = OpenCvSharp::CvRect( unmanaged.x, unmanaged.y, unmanaged.width, unmanaged.height ); return managed; } CFaceSelect *pFaceSearch; }; }
[ "shenbinsc@cbf8b9f2-3a65-11de-be05-5f7a86268029" ]
[ [ [ 1, 219 ] ] ]
80b7ee5fe55d54b71c83626e1856c9b625474dec
21868e763ab7ee92486a16164ccf907328123c00
/cssdocument.cpp
06bbe1b587ad2fed524c78ff68d64301a9787943
[]
no_license
nodesman/flare
73aacd54b5b59480901164f83905cf6cc77fe2bb
ba95fbfdeec1d557056054cbf007bf485c8144a6
refs/heads/master
2020-05-09T11:17:15.929029
2011-11-26T16:54:07
2011-11-26T16:54:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,936
cpp
#include "cssdocument.h" #include "codeeditor.h" #include "settings.h" #include "document.h" #include "completer.h" #include "globals.h" CSSDocument::CSSDocument(QString filename,Foundry *parent) { this->setWindowState(Qt::WindowMaximized); this->setParent(parent); this->initialize(); QFile theFile(filename); theFile.open(QIODevice::ReadOnly); QTextStream reader(&theFile); QString theText = reader.readAll(); this->editor->setPlainText(theText); } void CSSDocument::initialize() { this->savedAtleastOnce = false; this->activateWindow(); this->changedSinceSave = false; this->editor = new CodeEditor(this); this->findDialog = new FindDialog(this); this->setAttribute(Qt::WA_DeleteOnClose); this->setWindowTitle(QString("Untitled-%1").arg(Document::numberOfNewDocuments)); connect(this->editor,SIGNAL(copyAvailable(bool)),this,SIGNAL(copyAvailable(bool))); connect(this->editor,SIGNAL(textChanged()),this,SIGNAL(documentChanged())); connect(this->editor,SIGNAL(textChanged()),this,SLOT(documentModified()) ); connect(this->editor,SIGNAL(undoAvailable(bool)),this,SIGNAL(undoAvailable(bool))); connect(this->editor,SIGNAL(redoAvailable(bool)),this,SIGNAL(redoAvailable(bool))); this->setWidget(this->editor); QStringListModel *words; this->setMinimumHeight(FL_DOCUMENT_MINIMUM_HEIGHT); this->setMinimumWidth(FL_DOCUMENT_MINIMUM_WIDTH); this->highlighter = new SyntaxHighlighter("CSS",this->editor->document()); QFile theCSSRuleFile(":/cssCodeCompletionRules.txt"); theCSSRuleFile.open(QIODevice::ReadOnly); QTextStream reader(&theCSSRuleFile); QStringList *theList = new QStringList(); while (!reader.atEnd()) { theList->append(reader.readLine()); } this->editor->setCompleterModel(theList); this->setWindowState(Qt::WindowMaximized); }
[ [ [ 1, 51 ] ] ]
76106449ab24a0bbe7373c2c28161f6f86b80fd4
335783c9e5837a1b626073d1288b492f9f6b057f
/source/fbxcmd/daomax/Exporter/BaseExporter.h
6426b4fd949dc78ac45dc580059f0d069dcaf26a
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
code-google-com/fbx4eclipse
110766ee9760029d5017536847e9f3dc09e6ebd2
cc494db4261d7d636f8c4d0313db3953b781e295
refs/heads/master
2016-09-08T01:55:57.195874
2009-12-03T20:35:48
2009-12-03T20:35:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,070
h
/********************************************************************** *< FILE: BaseExporter.h DESCRIPTION: Base Exporter class HISTORY: *> Copyright (c) 2009, All Rights Reserved. **********************************************************************/ #pragma once // Exporter Base class BaseExporter { public: _tstring name; _tstring path; ExpInterface *i; Interface *gi; BOOL suppressPrompts; bool iniFileValid; _tstring iniFileName; DWORD options; BaseExporter(){} void BaseInit(const TCHAR *Name,ExpInterface *I,Interface *GI, BOOL SuppressPrompts, DWORD options) { name = Name; i=I; gi=GI; suppressPrompts = SuppressPrompts; char buffer[MAX_PATH] = {0}, *p = NULL; GetFullPathName(Name, _countof(buffer), buffer, &p); if (p) *p = 0; path = buffer; iniFileValid = false; this->options = options; Initialize(); } virtual void Initialize() = 0; virtual bool isValid() const { return true; } };
[ "tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792" ]
[ [ [ 1, 48 ] ] ]
02eba08aaf8edc868d94f39752b70d4484db17bf
b799c972367cd014a1ffed4288a9deb72f590bec
/project/NetServices/drv/gprs/GPRSModem.h
57dc49922c07d96dded0d06927519c0df41ec50f
[]
no_license
intervigilium/csm213a-embedded
647087de8f831e3c69e05d847d09f5fa12b468e6
ae4622be1eef8eb6e4d1677a9b2904921be19a9e
refs/heads/master
2021-01-13T02:22:42.397072
2011-12-11T22:50:37
2011-12-11T22:50:37
2,832,079
2
1
null
null
null
null
UTF-8
C++
false
false
1,669
h
/* Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef GPRSMODEM_H #define GPRSMODEM_H #include "drv/at/ATIf.h" enum GPRSErr { __GPRS_MIN = -0xFFFF, GPRS_MODEM, //ATErr returned GPRS_DENIED, GPRS_NONETWORK, GPRS_REGISTERING, GPRS_OK = 0 }; class GPRSModem : public ATIf { public: GPRSModem(); virtual ~GPRSModem(); GPRSErr getNetworkState(); GPRSErr setNetworkUp(); GPRSErr getGPRSState(); GPRSErr setGPRSUp(); GPRSErr setGPRSDown(); GPRSErr connect(const char* apn = NULL); GPRSErr disconnect(); }; #endif
[ [ [ 1, 57 ] ] ]
88fd46cb6b02ac20c815da5ed2ab3356ac3046ff
e67ac6db3204e1acdd1cd16178905f63e4510b34
/Empty project/Src/Core Code/bindToLua.cpp
22cb8290b450da8021cdbd7c4ffc1b3c11d61b0e
[]
no_license
nesa24/bgf3d
fd4959a0d838ff3811de7960630de16f53968c51
6e1aa4d451c7f0a1d56c555f6c75b09be6cf1941
refs/heads/master
2020-05-02T01:55:48.781811
2009-05-21T13:47:28
2009-05-21T13:47:28
32,896,083
0
0
null
null
null
null
UTF-8
C++
false
false
5,064
cpp
#include "StdAfx.h" #include <luabind/lua_include.hpp> #include <luabind/luabind.hpp> #include <luabind/class.hpp> // A global lua state lua_State* g_L; // get canvas Canvas* getCanvas( void ) { return g_pCanvas; } // get audio Audio* getAudio( void ) { return g_pAudio; } // function go register functions and classes to lua void bind2lua( void ) { using namespace luabind; using namespace std; // open lua state g_L = lua_open(); luabind::open( g_L ); lua_baselibopen(g_L); lua_iolibopen(g_L); lua_strlibopen(g_L); lua_mathlibopen(g_L); // bind Phase, PhaseManager, PhaseFactory, Panel // Object, ObjectFacroty to lua module( g_L ) [ class_< POINT >( "Point" ) .def( constructor<>() ) .def_readwrite( "x", &POINT::x ) .def_readwrite( "y", &POINT::y ), class_<PicLocation>( "PicLocation" ) .def( constructor<>() ) .def_readwrite( "m_iPicID", &PicLocation::m_iPicID ) .def_readwrite( "m_iTop", &PicLocation::m_iTop ) .def_readwrite( "m_iLeft", &PicLocation::m_iLeft ) .def_readwrite( "m_iBottom", &PicLocation::m_iBottom ) .def_readwrite( "m_iRight", &PicLocation::m_iRight ), class_< Phase >( "Phase" ) .def( "AddPanel", &Phase::AddPanel ) .def( "GetPanel", &Phase::GetPanel ) .def( "SetName", &Phase::SetName ), class_< Object >( "Object" ) .def( "SetLayer", &Object::SetLayer) .def( "SetSize", &Object::SetSize ) .def( "SetEnable", &Object::SetEnable ) .def( "SetVisible", &Object::SetVisible ) .def( "GetVisible", &Object::GetVisible ) .def( "SetPosCenter", &Object::SetPosCenter ) .def( "SetPosLT", &Object::SetPosLT ) .def( "SetPosCompare", &Object::SetPosCompare ) .def( "AddPicLocation", &Object::AddPicLocation ) .def( "SetPicIndex", &Object::SetPicIndex ) .def( "SetDataGroupByIndex", &Object::SetDataGroupByIndex ) .def( "SetBoolGroupByIndex", &Object::SetBoolGroupByIndex ) .def( "GetLayer", &Object::GetLayer ) .def( "SetPicIndex", &Object::SetPicIndex ) .def( "SetColorRGB", &Object::SetColorRGB ) .def( "SetFocusFunc", &Object::SetFocusFunc) .def( "SetLoseFocusFunc", &Object::SetLoseFocusFunc), def( "ParseButton", &Object::Parse< ObjButton > ), def( "ParseStaticText", &Object::Parse< StaticText > ), def( "ParseEditBox", &Object::Parse< EditBox > ), def( "ParsePanel", &Object::Parse< Panel > ), class_<Panel, Object>("Panel") .def( "AddObject", &Panel::AddObject ) .def( "SetName", &Panel::SetName ), class_< ObjUI, Object >( "ObjUI" ), class_< ObjButton, ObjUI >( "ObjButton" ) .def( "SetFun", &ObjButton::SetFun ) .def( "PushStrParam", &ObjButton::PushStrParam ) .def( "PushIntParam", &ObjButton::PushIntParam ), class_< StaticText, ObjUI >( "StaticText" ) .def( "SetContentStr", &StaticText::SetContentStr ) .def( "SetTextID", &StaticText::SetTextID ) .def( "SetName", &StaticText::SetName ) .def( "SetLine", &StaticText::SetLine ) .def( "GetLine", &StaticText::GetLine ) .def( "SetCharLength", &StaticText::SetCharLength ), class_< EditBox, ObjUI >( "EditBox" ) .def( "InitFinish", &EditBox::InitFinish ) .def( "SetLock", &EditBox::SetLock ) .def( "SetPassWord", &EditBox::SetPassWord ) .def( "SetMaxLength", &EditBox::SetMaxLength ), def( "OFinstance", &singObjectFactory::instance ), def( "PFinstance", &singPhaseFactory::instance ), def( "PMinstance", &singPhaseManager::instance ), def( "getCanvas", &getCanvas ), def( "getAudio", &getAudio ), class_< ObjectFactory >( "ObjectFactory" ), class_< PhaseFactory >( "PhaseFactory" ), class_< PhaseManager >( "PhaseManager" ), class_< ActionModule >( "ActionModule" ), class_<Canvas>( "Canvas" ) .def( "AddPicRes", &Canvas::AddPicRes ) .def( "AddFont", &Canvas::AddFont ), class_<Audio>( "Audio" ) .def( "AddSoundRes", &Audio::AddSoundRes ) .def( "PlayMusic", &Audio::PlayMusic ) .def( "StopMusic", &Audio::StopMusic ) .def( "AddMusicRes", &Audio::AddMusicRes ) .def( "SetSoundVolume", &Audio::SetSoundVolume) .def( "SoundOn", &Audio::SoundOn ) .def( "SoundOff", &Audio::SoundOff ) .def( "PlayGameSound", &Audio::PlayGameSound ), class_<singObjectFactory, ObjectFactory>( "ObjectFactory" ) .def( "Create", &singObjectFactory::Create ), class_<singPhaseFactory, PhaseFactory>( "PhaseFactory" ) .def( "Create", &singPhaseFactory::Create ), class_<singPhaseManager, PhaseManager >("PhaseManager") .def( "GetPhase", &singPhaseManager::GetThePhase ) .def( "AddPhase", &singPhaseManager::AddPhase ) .def( "ChangeToPhase", &singPhaseManager::ChangeToPhase), class_< vector<string> >( "strVector" ) .def( "push_back", &vector<string>::push_back ), class_< vector<int> >( "intVector" ) .def( "push_back", &vector<int>::push_back ), // bind your own button-action function class_< singActionModule, ActionModule >( "ActionModule" ), def( "btnExit", &singActionModule::btnExit ), def( "xtrace", &Out ) ]; }
[ "lyDASHsBOK@579413f5-764d-0410-af70-c34dc4d35548" ]
[ [ [ 1, 154 ] ] ]
3a5dbbe1c06cd8b9a5ac5a617cae1db278bd7795
b24d5382e0575ad5f7c6e5a77ed065d04b77d9fa
/GCore/GCore/GC_FixedTimeProvider.h
7ac6f037ef0670d5153bdef5a8aa6ff7fe75b6fd
[]
no_license
Klaim/radiant-laser-cross
f65571018bf612820415e0f672c216caf35de439
bf26a3a417412c0e1b77267b4a198e514b2c7915
refs/heads/master
2021-01-01T18:06:58.019414
2010-11-06T14:56:11
2010-11-06T14:56:11
32,205,098
0
0
null
null
null
null
UTF-8
C++
false
false
1,074
h
#ifndef GCORE_FIXEDTIMEPROVIDER_H #define GCORE_FIXEDTIMEPROVIDER_H #pragma once #include "GC_Common.h" #include "GC_TimeReference.h" namespace gcore { /** Provide time based on a fixed time update. Used for debugging time dependant features. */ class FixedTimeProvider : public TimeReference { public: /** Constructor. */ FixedTimeProvider( TimeValue fixedTime ) : TimeReference() , m_fixedTime( fixedTime ) , m_currentTimeSinceStart( 0 ) { } /** Destructor. */ ~FixedTimeProvider(){} /** Time passed since the system started (or other base time reference, implementation-specific). @return Time value (in seconds). */ TimeValue getTimeSinceStart() const { m_currentTimeSinceStart += m_fixedTime; return m_currentTimeSinceStart; } protected: private: /// Fixed time used to increment the current time each time const TimeValue m_fixedTime; /// Virtual time passed since the system start. mutable TimeValue m_currentTimeSinceStart; }; } #endif
[ [ [ 1, 55 ] ] ]
fccc345431be028ce6cb928b44a6ed034105b52d
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/200904/20090420-银行系统.cpp
bdcb04a231a722b41d84a0582d492a1e0d10e3fd
[]
no_license
lzq123218/guoyishi-works
dbfa42a3e2d3bd4a984a5681e4335814657551ef
4e78c8f2e902589c3f06387374024225f52e5a92
refs/heads/master
2021-12-04T11:11:32.639076
2011-05-30T14:12:43
2011-05-30T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
110
cpp
//20090420 #include <iostream> #include <string> #include <vector> using namespace std; int main() {
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 8 ] ] ]
58eff5c1eaabe434a3bb7958f19f6648aa639513
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Renderers/DX/WmlDxWireframeState.cpp
eb9f983a5a72808d465d594f9921bd48336cd157
[]
no_license
argapratama/kucgbowling
20dbaefe1596358156691e81ccceb9151b15efb0
65e40b6f33c5511bddf0fa350c1eefc647ace48a
refs/heads/master
2018-01-08T15:27:44.784437
2011-06-19T15:23:39
2011-06-19T15:23:39
36,738,655
0
0
null
null
null
null
UTF-8
C++
false
false
1,023
cpp
// 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. #include "WmlDxRenderer.h" using namespace Wml; //---------------------------------------------------------------------------- void DxRenderer::SetWireframeState (WireframeState* pkState) { if ( pkState->Enabled() ) { ms_hResult = m_pqDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME); WML_DX_ERROR_CHECK(SetRenderState); } else { ms_hResult = m_pqDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); WML_DX_ERROR_CHECK(SetRenderState); } } //----------------------------------------------------------------------------
[ [ [ 1, 30 ] ] ]
08afef893e5ec2688cdd9af89381d74973319808
1092bd6dc9b728f3789ba96e37e51cdfb9e19301
/loci/mocaps/bvh_document.cpp
88ded2d152a354307958f0aa938929ec8d1a76b9
[]
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
11,167
cpp
/** * Implementation of bvh_document. * Implements the bvh_document class. * * @file bvh_document.cpp * @author David Gill * @date 21/02/2010 */ #include <string> #include <istream> #include <sstream> #include <fstream> #include <iterator> #include <iostream> // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #include "loci/mocaps/bvh_document.h" #include "loci/pose.h" #include "loci/named_indices.h" #include "loci/hierarchy.h" #include "loci/skeleton.h" #include "loci/skeleton_builder.h" #include "loci/anim/keyed_motion.h" #include "loci/numeric/vector.h" #include "loci/numeric/quat.h" #include "loci/numeric/euler.h" #include "loci/numeric/convert/axisangle_quat.h" #include "loci/numeric/convert/euler_quat.h" #include "loci/numeric/transform/by_quat.h" #include "loci/mocaps/detail/bvh/scope.h" #include "loci/mocaps/detail/bvh/parser.h" #include "loci/mocaps/detail/bvh/save.h" namespace loci { namespace mocaps { namespace // anonymous { void compile_channels(loci::numeric::vector3f & position, loci::numeric::quatf & rotation, detail::bvh::scope_list::const_iterator pos, unsigned int frame) { using namespace loci::numeric; typedef detail::bvh::scope::channel_index_list::const_iterator channel_iterator; typedef detail::bvh::scope::motion_channel_list::const_iterator motion_iterator; typedef detail::bvh::channel_indices channel_indices; unsigned int euler_index = 0; static const unsigned int num_axis = 3; quatf euler_rotations[num_axis] = { quatf(1, 0, 0, 0), quatf(1, 0, 0, 0), quatf(1, 0, 0, 0) }; position = pos->offset; channel_iterator channel_iter = pos->channels.begin(); motion_iterator motion_iter = pos->motion.begin() + pos->channels.size() * frame; while (channel_iter != pos->channels.end() && euler_index < num_axis) { if (*channel_iter == channel_indices::x_position) { position.x(*motion_iter); } else if (*channel_iter == channel_indices::y_position) { position.y(*motion_iter); } else if (*channel_iter == channel_indices::z_position) { position.z(*motion_iter); } else if (*channel_iter == channel_indices::x_rotation) { euler_rotations[euler_index++] = convert::quat_from_axisangle(vector3f(1.0, 0.0, 0.0), *motion_iter); } else if (*channel_iter == channel_indices::y_rotation) { euler_rotations[euler_index++] = convert::quat_from_axisangle(vector3f(0.0, 1.0, 0.0), *motion_iter); } else if (*channel_iter == channel_indices::z_rotation) { euler_rotations[euler_index++] = convert::quat_from_axisangle(vector3f(0.0, 0.0, 1.0), *motion_iter); } ++channel_iter; ++motion_iter; } //position += pos->offset; rotation = euler_rotations[0] * euler_rotations[1] * euler_rotations[2]; } } // anonymous namespace bvh_document::bvh_document(const skeleton & figure, double frame_time, double expected_duration) : sample_rate(1000.0 * frame_time) , frame_count(0) { scopes.reserve(figure.bind_pose()->bone_count()); build_hierarchy_part(*figure.name_bindings(), *figure.bind_pose(), figure.structure()->root(), 0, static_cast<unsigned int>(expected_duration / frame_time + 1)); } bvh_document::bvh_document(std::istream & source) { parse(source); } bvh_document::bvh_document(const std::string & content) { std::istringstream iss(content); parse(iss); } bvh_document::mocap bvh_document::compile(bool first_frame_as_bind_pose) const { skeleton s = compile_skeleton(); std::auto_ptr<motion_type> m = compile_motion(first_frame_as_bind_pose); return mocap(s, m); } void bvh_document::save(std::ostream & sink) const { detail::bvh::save(sink, scopes, frame_count, static_cast<float>(sample_rate / 1000.0)); } void bvh_document::append_frame(const pose & p) { scope_list::iterator scope_iter = scopes.begin(); pose::const_bone_iterator bone_iter = p.begin(); scope_iter->motion.push_back( bone_iter->tip_offset.x() ); scope_iter->motion.push_back( bone_iter->tip_offset.y() ); scope_iter->motion.push_back( bone_iter->tip_offset.z() ); numeric::eulerf rot; for (; bone_iter != p.end() && scope_iter != scopes.end(); ++scope_iter, ++bone_iter) { rot = numeric::convert::to_euler_xyz(bone_iter->rotation); scope_iter->motion.push_back( rot.y() ); scope_iter->motion.push_back( rot.z() ); scope_iter->motion.push_back( rot.x() ); } ++frame_count; } void bvh_document::parse(std::istream & source) { float sample_rate_secs; detail::bvh::parse(source, scopes, frame_count, sample_rate_secs); sample_rate = 1000.0 * static_cast<double>(sample_rate_secs); } skeleton bvh_document::compile_skeleton() const { typedef numeric::quatf rotation; skeleton_builder builder( scopes[0].name, bone_pose( rotation(1, 0, 0, 0), scopes[0].offset )); scope_list::const_iterator iter = scopes.begin(); compile_skeleton_recurse(builder, builder.root(), iter, numeric::vector3f(0, 1, 0)); return builder.build(); } void bvh_document::compile_skeleton_recurse(skeleton_builder & builder, cursor parent, scope_iterator & pos, const numeric::vector3f & up) const { const std::string & parent_name = pos->name; const unsigned int depth = pos->depth + 1; unsigned int bone_id = 0; ++pos; while(pos != scopes.end() && pos->depth == depth) { std::ostringstream bone_name; bone_name << parent_name << " " << ++bone_id; numeric::vector3f direction = numeric::try_normalise(pos->offset, up); cursor joint = builder.add_bone( parent, bone_name.str(), bone_pose( numeric::quatf(1, 0, 0, 0), pos->offset)); if ( pos->end_site() ) { ++pos; continue; } compile_skeleton_recurse(builder, joint, pos, direction); } } std::auto_ptr<bvh_document::motion_type> bvh_document::compile_motion(bool first_frame_as_bind_pose) const { unsigned int frame_count_offset = first_frame_as_bind_pose ? 1 : 0; std::auto_ptr<motion_type> motion(new motion_type(frame_count - frame_count_offset)); for (unsigned int frame = frame_count_offset; frame < frame_count; ++frame) { std::auto_ptr<pose::bone_list> bones(new pose::bone_list()); bones->reserve(scopes.size()); scope_iterator pos = scopes.begin(); numeric::vector3f position; numeric::quatf rotation; compile_channels(position, rotation, pos, frame); bones->push_back(bone_pose(rotation, position)); compile_bone_motion_recurse(*bones, pos, frame); std::auto_ptr<pose> frame_pose( new pose(bones) ); motion->insert( static_cast<motion_type::time_type>(frame) * sample_rate, frame_pose); } return motion; } void bvh_document::compile_bone_motion_recurse(pose::bone_list & bones, scope_iterator & pos, unsigned int frame) const { const unsigned int depth = pos->depth + 1; ++pos; while(pos != scopes.end() && pos->depth == depth) { numeric::vector3f tip_offset; numeric::quatf rotation; compile_channels(tip_offset, rotation, pos, frame); bones.push_back( bone_pose(rotation, tip_offset) ); if ( pos->end_site() ) { ++pos; continue; } compile_bone_motion_recurse(bones, pos, frame); } } void bvh_document::build_hierarchy_part(const named_indices & name_bindings, const pose & bind_pose, cursor c, unsigned int depth, unsigned int motion_reserve) { if (depth > 0 && !scopes.back().end_site()) { std::stringstream bone_name; bone_name << name_bindings.name_of(c.position()); bone_name >> scopes.back().name; } scopes.push_back( detail::bvh::scope( numeric::transform::rotated_vector(bind_pose[c.position()].tip_offset, bind_pose[c.position()].rotation), depth, motion_reserve)); c.to_children(); if (c.valid()) // if it's a joint and not an end-site then add channels { // set the channel ordering: "[xpos ypos zpos] zrot xrot yrot" detail::bvh::scope & s = scopes.back(); if (depth == 0) { s.channels.push_back( detail::bvh::channel_indices::x_position ); s.channels.push_back( detail::bvh::channel_indices::y_position ); s.channels.push_back( detail::bvh::channel_indices::z_position ); } s.channels.push_back( detail::bvh::channel_indices::y_rotation ); s.channels.push_back( detail::bvh::channel_indices::z_rotation ); s.channels.push_back( detail::bvh::channel_indices::x_rotation ); } while (c.valid()) { build_hierarchy_part(name_bindings, bind_pose, c, depth+1, motion_reserve); c.next(); } } bvh_document::mocap import_bvh_file(const std::string & path, bool first_frame_as_bind_pose) { std::ifstream ifs(path.c_str()); return bvh_document(ifs).compile(first_frame_as_bind_pose); } void export_bvh_to_file(const bvh_document & bvh_doc, const std::string & path) { std::ofstream ofs(path.c_str()); bvh_doc.save(ofs); } } // namespace mocaps } // namespace loci
[ "[email protected]@0e8bac56-0901-9d1a-f0c4-3841fc69e132" ]
[ [ [ 1, 314 ] ] ]
7216e48217ca1bf96c72a6ef109bcf31cf1270ae
1092bd6dc9b728f3789ba96e37e51cdfb9e19301
/loci/video/scene_setup.cpp
18090519b1117da13f1512b87cfec4a1ce91250e
[]
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
3,811
cpp
#include <boost/shared_ptr.hpp> #include <boost/make_shared.hpp> #include <d3dx9.h> #include "loci/platform/win32/windows_common.h" #include "loci/platform/tstring.h" #include "loci/video/d3d9/device_services.h" #include "loci/video/d3d9/display_settings.h" #include "loci/video/d3d9/scene_presenter.h" #include "loci/video/d3d9/reset_service.h" #include "loci/video/d3d9/fixed_function_pipeline.h" #include "loci/video/d3d9/sphere.h" #include "loci/video/d3d9/vertex_buffer_allocator.h" #include "loci/video/d3d9/primitive_drawer.h" #include "loci/video/d3d9/font_map.h" #include "loci/video/renderers/renderer.h" #include "loci/video/renderers/joint_renderer.h" #include "loci/video/renderers/arena_renderer.h" #include "loci/video/renderers/simple_mesh_renderer.h" #include "loci/video/renderers/drawer.h" #include "loci/video/resources/mesh.h" #include "loci/video/resources/obj_loader.h" #include "loci/video/resources/texture_factory.h" namespace loci { namespace video { renderer setup_scene_renderer(HWND output_window, const d3d9::display_settings & config, const platform::tstring & font_name, unsigned int font_size, unsigned int slices, unsigned int stacks, const std::string & scene_path, float scale) { boost::shared_ptr<d3d9::device_services> device = d3d9::create_shared_device(output_window, config); d3d9::fixed_function_pipeline pipeline(device); static const float unit_sphere_radius = 0.5f; boost::shared_ptr<d3d9::sphere> sphere( boost::make_shared<d3d9::sphere>(device, unit_sphere_radius, slices, stacks)); D3DXMATRIX mesh_transform; create_bone_transform(mesh_transform, unit_sphere_radius, unit_sphere_radius); boost::shared_ptr<scene_renderer> scene; if (scene_path.empty()) { scene = boost::make_shared<arena_renderer>( d3d9::vertex_buffer_allocator(device), d3d9::primitive_drawer(device), pipeline, 100, 100, 100, 100); } else { vertex_array va; materials_list ml; texture_factory textures(device); parse_obj(va, ml, textures, scene_path, true); scene = boost::make_shared<simple_mesh_renderer>( va, ml, scale, textures, d3d9::vertex_buffer_allocator(device), d3d9::primitive_drawer(device), pipeline); } return renderer( config, d3d9::scene_presenter(device), d3d9::reset_service(device), pipeline, scene, joint_renderer( sphere, mesh_transform, pipeline), boost::make_shared<d3d9::font_map>(device, font_name, font_size), sphere); } renderer setup_scene_renderer(HWND output_window, const d3d9::display_settings & config, const std::string & scene_path, float scale) { return setup_scene_renderer(output_window, config, LOCI_TSTR("Century Gothic"), 20, 10, 10, scene_path, scale); } } // namespace video } // namespace loci
[ "[email protected]@0e8bac56-0901-9d1a-f0c4-3841fc69e132" ]
[ [ [ 1, 105 ] ] ]
47659943be3742e54555ed56d244485b45ef8044
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/dom/deprecated/DOMParser.hpp
1c885d02d7508d00a6f3108aa0b1ec1a06a2e9a8
[ "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
73,636
hpp
/* * 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: DOMParser.hpp,v 1.25 2004/09/08 13:55:42 peiyongz Exp $ * */ #if !defined(DOMPARSER_HPP) #define DOMPARSER_HPP #include <xercesc/framework/XMLDocumentHandler.hpp> #include <xercesc/framework/XMLErrorReporter.hpp> #include <xercesc/framework/XMLEntityHandler.hpp> #include <xercesc/util/ValueStackOf.hpp> #include <xercesc/validators/DTD/DocTypeHandler.hpp> #include <xercesc/validators/DTD/DTDElementDecl.hpp> #include "DOM_Document.hpp" #include "DOM_DocumentType.hpp" XERCES_CPP_NAMESPACE_BEGIN class EntityResolver; class ErrorHandler; class XMLPScanToken; class XMLScanner; class XMLValidator; class Grammar; class GrammarResolver; class XMLGrammarPool; class XMLEntityResolver; class PSVIHandler; /** * This class implements the Document Object Model (DOM) interface. * It should be used by applications which choose to parse and * process the XML document using the DOM api's. This implementation * also allows the applications to install an error and an entitty * handler (useful extensions to the DOM specification). * * <p>It can be used to instantiate a validating or non-validating * parser, by setting a member flag.</p> */ class DEPRECATED_DOM_EXPORT DOMParser : public XMLDocumentHandler , public XMLErrorReporter , public XMLEntityHandler , public DocTypeHandler , public XMemory { public : // ----------------------------------------------------------------------- // Class types // ----------------------------------------------------------------------- enum ValSchemes { Val_Never , Val_Always , Val_Auto }; // ----------------------------------------------------------------------- // Constructors and Detructor // ----------------------------------------------------------------------- /** @name Constructors and Destructor */ //@{ /** Construct a DOMParser, with an optional validator * * Constructor with an instance of validator class to use for * validation. If you don't provide a validator, a default one will * be created for you in the scanner. * * @param valToAdopt Pointer to the validator instance to use. The * parser is responsible for freeing the memory. */ DOMParser ( XMLValidator* const valToAdopt = 0 , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager , XMLGrammarPool* const gramPool = 0 ); /** * Destructor */ ~DOMParser(); //@} /** Reset the parser * * This method resets the state of the DOM driver and makes * it ready for a fresh parse run. */ void reset(); // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- /** @name Getter methods */ //@{ /** Get the DOM document * * This method returns the DOM_Document object representing the * root of the document tree. This object provides the primary * access to the document's data. * * @return The DOM_Document object which represents the entire * XML document. */ DOM_Document getDocument(); /** Get a pointer to the error handler * * This method returns the installed error handler. If no handler * has been installed, then it will be a zero pointer. * * @return The pointer to the installed error handler object. */ ErrorHandler* getErrorHandler(); /** Get a const pointer to the error handler * * This method returns the installed error handler. If no handler * has been installed, then it will be a zero pointer. * * @return A const pointer to the installed error handler object. */ const ErrorHandler* getErrorHandler() const; /** Get a pointer to the PSVI handler * * This method returns the installed PSVI handler. If no handler * has been installed, then it will be a zero pointer. * * @return The pointer to the installed PSVI handler object. */ PSVIHandler* getPSVIHandler(); /** Get a const pointer to the error handler * * This method returns the installed error handler. If no handler * has been installed, then it will be a zero pointer. * * @return A const pointer to the installed error handler object. */ const PSVIHandler* getPSVIHandler() const; /** Get a pointer to the entity resolver * * This method returns the installed entity resolver. If no resolver * has been installed, then it will be a zero pointer. * * @return The pointer to the installed entity resolver object. */ EntityResolver* getEntityResolver(); /** Get a const pointer to the entity resolver * * This method returns the installed entity resolver. If no resolver * has been installed, then it will be a zero pointer. * * @return A const pointer to the installed entity resolver object. */ const EntityResolver* getEntityResolver() const; /** Get a pointer to the entity resolver * * This method returns the installed entity resolver. If no resolver * has been installed, then it will be a zero pointer. * * @return The pointer to the installed entity resolver object. */ XMLEntityResolver* getXMLEntityResolver(); /** Get a const pointer to the entity resolver * * This method returns the installed entity resolver. If no resolver * has been installed, then it will be a zero pointer. * * @return A const pointer to the installed entity resolver object. */ const XMLEntityResolver* getXMLEntityResolver() const; /** Get a const reference to the underlying scanner * * This method returns a reference to the underlying scanner object. * It allows read only access to data maintained in the scanner. * * @return A const reference to the underlying scanner object. */ const XMLScanner& getScanner() const; /** Get a const reference to the validator * * This method returns a reference to the parser's installed * validator. * * @return A const reference to the installed validator object. */ const XMLValidator& getValidator() const; /** * This method returns an enumerated value that indicates the current * validation scheme set on this parser. * * @return The ValSchemes value current set on this parser. * @see #setValidationScheme */ ValSchemes getValidationScheme() const; /** Get the 'do schema' flag * * This method returns the state of the parser's schema processing * flag. * * @return true, if the parser is currently configured to * understand schema, false otherwise. * * @see #setDoSchema */ bool getDoSchema() const; /** Get the 'full schema constraint checking' flag * * This method returns the state of the parser's full schema constraint * checking flag. * * @return true, if the parser is currently configured to * have full schema constraint checking, false otherwise. * * @see #setValidationSchemaFullChecking */ bool getValidationSchemaFullChecking() const; bool getIdentityConstraintChecking() const; /** Get error count from the last parse operation. * * This method returns the error count from the last parse * operation. Note that this count is actually stored in the * scanner, so this method simply returns what the * scanner reports. * * @return number of errors encountered during the latest * parse operation. * */ int getErrorCount() const; /** Get the 'do namespaces' flag * * This method returns the state of the parser's namespace processing * flag. * * @return true, if the parser is currently configured to * understand namespaces, false otherwise. * * @see #setDoNamespaces */ bool getDoNamespaces() const; /** Get the 'exit on first error' flag * * This method returns the state of the parser's * exit-on-First-Fatal-Error flag. If this flag is true, then the * parse will exit the first time it sees any non-wellformed XML or * any validity error. The default state is true. * * @return true, if the parser is currently configured to * exit on the first fatal error, false otherwise. * * @see #setExitOnFirstFatalError */ bool getExitOnFirstFatalError() const; /** * This method returns the state of the parser's * validation-constraint-fatal flag. * * @return true, if the parser is currently configured to * set validation constraint errors as fatal, false * otherwise. * * @see #setValidationContraintFatal */ bool getValidationConstraintFatal() const; /** Get the 'include entity references' flag * * This method returns the flag that specifies whether the parser is * creating entity reference nodes in the DOM tree being produced. * * @return The state of the create entity reference node * flag. * @see #setCreateEntityReferenceNodes */ bool getCreateEntityReferenceNodes()const; /** Get the 'include ignorable whitespace' flag. * * This method returns the state of the parser's include ignorable * whitespace flag. * * @return 'true' if the include ignorable whitespace flag is set on * the parser, 'false' otherwise. * * @see #setIncludeIgnorableWhitespace */ bool getIncludeIgnorableWhitespace() const; /** Get the 'to create MXLDecl node' flag. * * This method returns the state of the parser's to create XMLDecl * DOM Node flag. * * @return 'true' if the toCreateXMLDeclTypeNode flag is set on * the parser, 'false' otherwise. * */ bool getToCreateXMLDeclTypeNode() const; /** Get the set of Namespace/SchemaLocation that is specified externaly. * * This method returns the list of Namespace/SchemaLocation that was * specified using setExternalSchemaLocation. * * The parser owns the returned string, and the memory allocated for * the returned string will be destroyed when the parser is deleted. * * To ensure assessiblity of the returned information after the parser * is deleted, callers need to copy and store the returned information * somewhere else. * * @return a pointer to the list of Namespace/SchemaLocation that was * specified externally. The pointer spans the same life-time as * the parser. A null pointer is returned if nothing * was specified externally. * * @see #setExternalSchemaLocation(const XMLCh* const) */ XMLCh* getExternalSchemaLocation() const; /** Get the noNamespace SchemaLocation that is specified externaly. * * This method returns the no target namespace XML Schema Location * that was specified using setExternalNoNamespaceSchemaLocation. * * The parser owns the returned string, and the memory allocated for * the returned string will be destroyed when the parser is deleted. * * To ensure assessiblity of the returned information after the parser * is deleted, callers need to copy and store the returned information * somewhere else. * * @return a pointer to the no target namespace Schema Location that was * specified externally. The pointer spans the same life-time as * the parser. A null pointer is returned if nothing * was specified externally. * * @see #setExternalNoNamespaceSchemaLocation(const XMLCh* const) */ XMLCh* getExternalNoNamespaceSchemaLocation() const; /** Get the 'Grammar caching' flag * * This method returns the state of the parser's grammar caching when * parsing an XML document. * * @return true, if the parser is currently configured to * cache grammars, false otherwise. * * @see #cacheGrammarFromParse */ bool isCachingGrammarFromParse() const; /** Get the 'Use cached grammar' flag * * This method returns the state of the parser's use of cached grammar * when parsing an XML document. * * @return true, if the parser is currently configured to * use cached grammars, false otherwise. * * @see #useCachedGrammarInParse */ bool isUsingCachedGrammarInParse() const; /** * Get the 'calculate src offset flag' * * This method returns the state of the parser's src offset calculation * when parsing an XML document. * * @return true, if the parser is currently configured to * calculate src offsets, false otherwise. * * @see #setCalculateSrcOfs */ bool getCalculateSrcOfs() const; /** * Get the 'force standard uri flag' * * This method returns the state if the parser forces standard uri * * @return true, if the parser is currently configured to * force standard uri, i.e. malformed uri will be rejected. * * @see #setStandardUriConformant */ bool getStandardUriConformant() const; /** * Retrieve the grammar that is associated with the specified namespace key * * @param nameSpaceKey Namespace key * @return Grammar associated with the Namespace key. */ Grammar* getGrammar(const XMLCh* const nameSpaceKey); /** * Retrieve the grammar where the root element is declared. * * @return Grammar where root element declared */ Grammar* getRootGrammar(); /** * Returns the string corresponding to a URI id from the URI string pool. * * @param uriId id of the string in the URI string pool. * @return URI string corresponding to the URI id. */ const XMLCh* getURIText(unsigned int uriId) const; /** * Returns the current src offset within the input source. * * @return offset within the input source */ unsigned int getSrcOffset() const; //@} // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- /** @name Setter methods */ //@{ /** Set the error handler * * This method allows applications to install their own error handler * to trap error and warning messages. * * <i>Any previously set handler is merely dropped, since the parser * does not own them.</i> * * @param handler A const pointer to the user supplied error * handler. * * @see #getErrorHandler */ void setErrorHandler(ErrorHandler* const handler); /** Set the PSVI handler * * This method allows applications to install their own PSVI handler. * * <i>Any previously set handler is merely dropped, since the parser * does not own them.</i> * * @param handler A const pointer to the user supplied PSVI * handler. * * @see #getPSVIHandler */ void setPSVIHandler(PSVIHandler* const handler); /** Set the entity resolver * * This method allows applications to install their own entity * resolver. By installing an entity resolver, the applications * can trap and potentially redirect references to external * entities. * * <i>Any previously set entity resolver is merely dropped, since the parser * does not own them. If both setEntityResolver and setXMLEntityResolver * are called, then the last one is used.</i> * * @param handler A const pointer to the user supplied entity * resolver. * * @see #getEntityResolver */ void setEntityResolver(EntityResolver* const handler); /** Set the entity resolver * * This method allows applications to install their own entity * resolver. By installing an entity resolver, the applications * can trap and potentially redirect references to external * entities. * * <i>Any previously set entity resolver is merely dropped, since the parser * does not own them. If both setEntityResolver and setXMLEntityResolver * are called, then the last one is used.</i> * * @param handler A const pointer to the user supplied entity * resolver. * * @see #getXMLEntityResolver */ void setXMLEntityResolver(XMLEntityResolver* const handler); /** Set the 'do namespaces' flag * * This method allows users to enable or disable the parser's * namespace processing. When set to true, parser starts enforcing * all the constraints and rules specified by the NameSpace * specification. * * The parser's default state is: false. * * @param newState The value specifying whether NameSpace rules should * be enforced or not. * * @see #getDoNamespaces */ void setDoNamespaces(const bool newState); /** Set the 'exit on first error' flag * * This method allows users to set the parser's behaviour when it * encounters the first fatal error. If set to true, the parser * will exit at the first fatal error. If false, then it will * report the error and continue processing. * * The default value is 'true' and the parser exits on the * first fatal error. * * @param newState The value specifying whether the parser should * continue or exit when it encounters the first * fatal error. * * @see #getExitOnFirstFatalError */ void setExitOnFirstFatalError(const bool newState); /** * This method allows users to set the parser's behaviour when it * encounters a validtion constraint error. If set to true, and the * the parser will treat validation error as fatal and will exit depends on the * state of "getExitOnFirstFatalError". If false, then it will * report the error and continue processing. * * Note: setting this true does not mean the validation error will be printed with * the word "Fatal Error". It is still printed as "Error", but the parser * will exit if "setExitOnFirstFatalError" is set to true. * * <p>The default value is 'false'.</p> * * @param newState If true, the parser will exit if "setExitOnFirstFatalError" * is set to true. * * @see #getValidationConstraintFatal * @see #setExitOnFirstFatalError */ void setValidationConstraintFatal(const bool newState); /** Set the 'include entity references' flag * * This method allows the user to specify whether the parser should * create entity reference nodes in the DOM tree being produced. * When the 'create' flag is * true, the parser will create EntityReference nodes in the DOM tree. * The EntityReference nodes and their child nodes will be read-only. * When the 'create' flag is false, no EntityReference nodes will be created. * <p>The replacement text * of the entity is included in either case, either as a * child of the Entity Reference node or in place at the location * of the reference. * <p>The default value is 'true'. * * @param create The new state of the create entity reference nodes * flag. * @see #getCreateEntityReferenceNodes */ void setCreateEntityReferenceNodes(const bool create); /** Set the 'include ignorable whitespace' flag * * This method allows the user to specify whether a validating parser * should include ignorable whitespaces as text nodes. It has no effect * on non-validating parsers which always include non-markup text. * <p>When set to true (also the default), ignorable whitespaces will be * added to the DOM tree as text nodes. The method * DOM_Text::isIgnorableWhitespace() will return true for those text * nodes only. * <p>When set to false, all ignorable whitespace will be discarded and * no text node is added to the DOM tree. Note: applications intended * to process the "xml:space" attribute should not set this flag to false. * And this flag also overrides any schema datateye whitespace facets, * that is, all ignorable whitespace will be discarded even though * 'preserve' is set in schema datatype whitespace facets. * * @param include The new state of the include ignorable whitespace * flag. * * @see #getIncludeIgnorableWhitespace */ void setIncludeIgnorableWhitespace(const bool include); /** * This method allows users to set the validation scheme to be used * by this parser. The value is one of the ValSchemes enumerated values * defined by this class: * * <br> Val_Never - turn off validation * <br> Val_Always - turn on validation * <br> Val_Auto - turn on validation if any internal/external * DTD subset have been seen * * <p>The parser's default state is: Val_Auto.</p> * * @param newScheme The new validation scheme to use. * * @see #getValidationScheme */ void setValidationScheme(const ValSchemes newScheme); /** Set the 'do schema' flag * * This method allows users to enable or disable the parser's * schema processing. When set to false, parser will not process * any schema found. * * The parser's default state is: false. * * Note: If set to true, namespace processing must also be turned on. * * @param newState The value specifying whether schema support should * be enforced or not. * * @see #getDoSchema */ void setDoSchema(const bool newState); /** * This method allows the user to turn full Schema constraint checking on/off. * Only takes effect if Schema validation is enabled. * If turned off, partial constraint checking is done. * * Full schema constraint checking includes those checking that may * be time-consuming or memory intensive. Currently, particle unique * attribution constraint checking and particle derivation resriction checking * are controlled by this option. * * The parser's default state is: false. * * @param schemaFullChecking True to turn on full schema constraint checking. * * @see #getValidationSchemaFullChecking */ void setValidationSchemaFullChecking(const bool schemaFullChecking); void setIdentityConstraintChecking(const bool identityConstraintChecking); /** * This method allows users to set the toCreateXMLDeclTypeNode flag * by this parser. By setting it to 'true' user can have XMLDecl type * nodes attached to the DOM tree. * * <p>The parser's default state is: false </p> * * @param create The new to create XMLDecl type node flag * */ void setToCreateXMLDeclTypeNode(const bool create); /** * This method allows the user to specify a list of schemas to use. * If the targetNamespace of a schema specified using this method matches * the targetNamespace of a schema occuring in the instance document in * the schemaLocation attribute, or if the targetNamespace matches the * namespace attribute of the "import" element, the schema specified by the * user using this method will be used (i.e., the schemaLocation attribute * in the instance document or on the "import" element will be effectively ignored). * * If this method is called more than once, only the last one takes effect. * * The syntax is the same as for schemaLocation attributes in instance * documents: e.g, "http://www.example.com file_name.xsd". The user can * specify more than one XML Schema in the list. * * @param schemaLocation the list of schemas to use * * @see #getExternalSchemaLocation */ void setExternalSchemaLocation(const XMLCh* const schemaLocation); /** * This method is same as setExternalSchemaLocation(const XMLCh* const). * It takes native char string as parameter * * @param schemaLocation the list of schemas to use * * @see #setExternalSchemaLocation(const XMLCh* const) */ void setExternalSchemaLocation(const char* const schemaLocation); /** * This method allows the user to specify the no target namespace XML * Schema Location externally. If specified, the instance document's * noNamespaceSchemaLocation attribute will be effectively ignored. * * If this method is called more than once, only the last one takes effect. * * The syntax is the same as for the noNamespaceSchemaLocation attribute * that may occur in an instance document: e.g."file_name.xsd". * * @param noNamespaceSchemaLocation the XML Schema Location with no target namespace * * @see #getExternalNoNamespaceSchemaLocation */ void setExternalNoNamespaceSchemaLocation(const XMLCh* const noNamespaceSchemaLocation); /** * This method is same as setExternalNoNamespaceSchemaLocation(const XMLCh* const). * It takes native char string as parameter * * @param noNamespaceSchemaLocation the XML Schema Location with no target namespace * * @see #setExternalNoNamespaceSchemaLocation(const XMLCh* const) */ void setExternalNoNamespaceSchemaLocation(const char* const noNamespaceSchemaLocation); /** Set the 'Grammar caching' flag * * This method allows users to enable or disable caching of grammar when * parsing XML documents. When set to true, the parser will cache the * resulting grammar for use in subsequent parses. * * If the flag is set to true, the 'Use cached grammar' flag will also be * set to true. * * The parser's default state is: false. * * @param newState The value specifying whether we should cache grammars * or not. * * @see #isCachingGrammarFromParse * @see #useCachedGrammarInParse */ void cacheGrammarFromParse(const bool newState); /** Set the 'Use cached grammar' flag * * This method allows users to enable or disable the use of cached * grammars. When set to true, the parser will use the cached grammar, * instead of building the grammar from scratch, to validate XML * documents. * * If the 'Grammar caching' flag is set to true, this mehod ignore the * value passed in. * * The parser's default state is: false. * * @param newState The value specifying whether we should use the cached * grammar or not. * * @see #isUsingCachedGrammarInParse * @see #cacheGrammarFromParse */ void useCachedGrammarInParse(const bool newState); /** Enable/disable src offset calculation * * This method allows users to enable/disable src offset calculation. * Disabling the calculation will improve performance. * * The parser's default state is: false. * * @param newState The value specifying whether we should enable or * disable src offset calculation * * @see #getCalculateSrcOfs */ void setCalculateSrcOfs(const bool newState); /** Force standard uri * * This method allows users to tell the parser to force standard uri conformance. * * The parser's default state is: false. * * @param newState The value specifying whether the parser should reject malformed URI. * * @see #getStandardUriConformant */ void setStandardUriConformant(const bool newState); /** Set the scanner to use when scanning the XML document * * This method allows users to set the scanner to use * when scanning a given XML document. * * @param scannerName The name of the desired scanner */ void useScanner(const XMLCh* const scannerName); //@} // ----------------------------------------------------------------------- // Parsing methods // ----------------------------------------------------------------------- /** @name Parsing methods */ //@{ /** Parse via an input source object * * This method invokes the parsing process on the XML file specified * by the InputSource parameter. This API is borrowed from the * SAX Parser interface. * * @param source A const reference to the InputSource object which * points to the XML file to be parsed. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @exception DOM_DOMException A DOM exception as per DOM spec. * @see InputSource#InputSource * @see #setEntityResolver * @see #setErrorHandler */ void parse(const InputSource& source); /** Parse via a file path or URL * * This method invokes the parsing process on the XML file specified by * the Unicode string parameter 'systemId'. This method is borrowed * from the SAX Parser interface. * * @param systemId A const XMLCh pointer to the Unicode string which * contains the path to the XML file to be parsed. * * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @exception DOM_DOMException A DOM exception as per DOM spec. * @see #parse(InputSource,...) */ void parse(const XMLCh* const systemId); /** Parse via a file path or URL (in the local code page) * * This method invokes the parsing process on the XML file specified by * the native char* string parameter 'systemId'. * * @param systemId A const char pointer to a native string which * contains the path to the XML file to be parsed. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @exception DOM_DOMException A DOM exception as per DOM spec. * @see #parse(InputSource,...) */ void parse(const char* const systemId); /** Begin a progressive parse operation * * This method is used to start a progressive parse on a XML file. * To continue parsing, subsequent calls must be to the parseNext * method. * * It scans through the prolog and returns a token to be used on * subsequent scanNext() calls. If the return value is true, then the * token is legal and ready for further use. If it returns false, then * the scan of the prolog failed and the token is not going to work on * subsequent scanNext() calls. * * @param systemId A pointer to a Unicode string represting the path * to the XML file to be parsed. * @param toFill A token maintaing state information to maintain * internal consistency between invocation of 'parseNext' * calls. * @return 'true', if successful in parsing the prolog. It indicates the * user can go ahead with parsing the rest of the file. It * returns 'false' to indicate that the parser could not parse * the prolog. * * @see #parseNext * @see #parseFirst(char*,...) * @see #parseFirst(InputSource&,...) */ bool parseFirst ( const XMLCh* const systemId , XMLPScanToken& toFill ); /** Begin a progressive parse operation * * This method is used to start a progressive parse on a XML file. * To continue parsing, subsequent calls must be to the parseNext * method. * * It scans through the prolog and returns a token to be used on * subsequent scanNext() calls. If the return value is true, then the * token is legal and ready for further use. If it returns false, then * the scan of the prolog failed and the token is not going to work on * subsequent scanNext() calls. * * @param systemId A pointer to a regular native string represting * the path to the XML file to be parsed. * @param toFill A token maintaing state information to maintain * internal consistency between invocation of 'parseNext' * calls. * * @return 'true', if successful in parsing the prolog. It indicates the * user can go ahead with parsing the rest of the file. It * returns 'false' to indicate that the parser could not parse * the prolog. * * @see #parseNext * @see #parseFirst(XMLCh*,...) * @see #parseFirst(InputSource&,...) */ bool parseFirst ( const char* const systemId , XMLPScanToken& toFill ); /** Begin a progressive parse operation * * This method is used to start a progressive parse on a XML file. * To continue parsing, subsequent calls must be to the parseNext * method. * * It scans through the prolog and returns a token to be used on * subsequent scanNext() calls. If the return value is true, then the * token is legal and ready for further use. If it returns false, then * the scan of the prolog failed and the token is not going to work on * subsequent scanNext() calls. * * @param source A const reference to the InputSource object which * points to the XML file to be parsed. * @param toFill A token maintaing state information to maintain * internal consistency between invocation of 'parseNext' * calls. * * @return 'true', if successful in parsing the prolog. It indicates the * user can go ahead with parsing the rest of the file. It * returns 'false' to indicate that the parser could not parse * the prolog. * * @see #parseNext * @see #parseFirst(XMLCh*,...) * @see #parseFirst(char*,...) */ bool parseFirst ( const InputSource& source , XMLPScanToken& toFill ); /** Continue a progressive parse operation * * This method is used to continue with progressive parsing of * XML files started by a call to 'parseFirst' method. * * It parses the XML file and stops as soon as it comes across * a XML token (as defined in the XML specification). * * @param token A token maintaing state information to maintain * internal consistency between invocation of 'parseNext' * calls. * * @return 'true', if successful in parsing the next XML token. * It indicates the user can go ahead with parsing the rest * of the file. It returns 'false' to indicate that the parser * could not find next token as per the XML specification * production rule. * * @see #parseFirst(XMLCh*,...) * @see #parseFirst(char*,...) * @see #parseFirst(InputSource&,...) */ bool parseNext(XMLPScanToken& token); /** Reset the parser after a progressive parse * * If a progressive parse loop exits before the end of the document * is reached, the parser has no way of knowing this. So it will leave * open any files or sockets or memory buffers that were in use at * the time that the parse loop exited. * * The next parse operation will cause these open files and such to * be closed, but the next parse operation might occur at some unknown * future point. To avoid this problem, you should reset the parser if * you exit the loop early. * * If you exited because of an error, then this cleanup will be done * for you. Its only when you exit the file prematurely of your own * accord, because you've found what you wanted in the file most * likely. * * @param token A token maintaing state information to maintain * internal consistency between invocation of 'parseNext' * calls. * * @see #parseFirst(XMLCh*,...) * @see #parseFirst(char*,...) * @see #parseFirst(InputSource&,...) */ void parseReset(XMLPScanToken& token); //@} // ----------------------------------------------------------------------- // Grammar preparsing interface // ----------------------------------------------------------------------- /** @name Implementation of Grammar preparsing interface's. */ //@{ /** * Preparse schema grammar (XML Schema, DTD, etc.) via an input source * object. * * This method invokes the preparsing process on a schema grammar XML * file specified by the SAX InputSource parameter. If the 'toCache' flag * is enabled, the parser will cache the grammars for re-use. If a grammar * key is found in the pool, no caching of any grammar will take place. * * <p><b>"Experimental - subject to change"</b></p> * * @param source A const reference to the SAX InputSource object which * points to the schema grammar file to be preparsed. * @param grammarType The grammar type (Schema or DTD). * @param toCache If <code>true</code>, we cache the preparsed grammar, * otherwise, no chaching. Default is <code>false</code>. * @return The preparsed schema grammar object (SchemaGrammar or * DTDGrammar). That grammar object is owned by the parser. * * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @exception DOMException A DOM exception as per DOM spec. * * @see InputSource#InputSource */ Grammar* loadGrammar(const InputSource& source, const short grammarType, const bool toCache = false); /** * Preparse schema grammar (XML Schema, DTD, etc.) via a file path or URL * * This method invokes the preparsing process on a schema grammar XML * file specified by the file path parameter. If the 'toCache' flag * is enabled, the parser will cache the grammars for re-use. If a grammar * key is found in the pool, no caching of any grammar will take place. * * <p><b>"Experimental - subject to change"</b></p> * * @param systemId A const XMLCh pointer to the Unicode string which * contains the path to the XML grammar file to be * preparsed. * @param grammarType The grammar type (Schema or DTD). * @param toCache If <code>true</code>, we cache the preparsed grammar, * otherwise, no chaching. Default is <code>false</code>. * @return The preparsed schema grammar object (SchemaGrammar or * DTDGrammar). That grammar object is owned by the parser. * * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @exception DOMException A DOM exception as per DOM spec. */ Grammar* loadGrammar(const XMLCh* const systemId, const short grammarType, const bool toCache = false); /** * Preparse schema grammar (XML Schema, DTD, etc.) via a file path or URL * * This method invokes the preparsing process on a schema grammar XML * file specified by the file path parameter. If the 'toCache' flag * is enabled, the parser will cache the grammars for re-use. If a grammar * key is found in the pool, no caching of any grammar will take place. * * <p><b>"Experimental - subject to change"</b></p> * * @param systemId A const char pointer to a native string which contains * the path to the XML grammar file to be preparsed. * @param grammarType The grammar type (Schema or DTD). * @param toCache If <code>true</code>, we cache the preparsed grammar, * otherwise, no chaching. Default is <code>false</code>. * @return The preparsed schema grammar object (SchemaGrammar or * DTDGrammar). That grammar object is owned by the parser. * * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @exception XMLException An exception from the parser or client * handler code. * @exception DOMException A DOM exception as per DOM spec. */ Grammar* loadGrammar(const char* const systemId, const short grammarType, const bool toCache = false); /** * This method allows the user to reset the pool of cached grammars. */ void resetCachedGrammarPool(); //@} // ----------------------------------------------------------------------- // Implementation of the XMLErrorReporter interface. // ----------------------------------------------------------------------- /** @name Implementation of the XMLErrorReporter interface. */ //@{ /** Handle errors reported from the parser * * This method is used to report back errors found while parsing the * XML file. This method is also borrowed from the SAX specification. * It calls the corresponding user installed Error Handler method: * 'fatal', 'error', 'warning' depending on the severity of the error. * This classification is defined by the XML specification. * * @param errCode An integer code for the error. * @param msgDomain A const pointer to an Unicode string representing * the message domain to use. * @param errType An enumeration classifying the severity of the error. * @param errorText A const pointer to an Unicode string representing * the text of the error message. * @param systemId A const pointer to an Unicode string representing * the system id of the XML file where this error * was discovered. * @param publicId A const pointer to an Unicode string representing * the public id of the XML file where this error * was discovered. * @param lineNum The line number where the error occurred. * @param colNum The column number where the error occurred. * @see ErrorHandler */ virtual void error ( const unsigned int errCode , const XMLCh* const msgDomain , const XMLErrorReporter::ErrTypes errType , const XMLCh* const errorText , const XMLCh* const systemId , const XMLCh* const publicId , const XMLSSize_t lineNum , const XMLSSize_t colNum ); /** Reset any error data before a new parse * * This method allows the user installed Error Handler callback to * 'reset' itself. * * <b><font color="#FF0000">This method is a no-op for this DOM * implementation.</font></b> */ virtual void resetErrors(); //@} // ----------------------------------------------------------------------- // Implementation of the XMLEntityHandler interface. // ----------------------------------------------------------------------- /** @name Implementation of the XMLEntityHandler interface. */ //@{ /** Handle an end of input source event * * This method is used to indicate the end of parsing of an external * entity file. * * <b><font color="#FF0000">This method is a no-op for this DOM * implementation.</font></b> * * @param inputSource A const reference to the InputSource object * which points to the XML file being parsed. * @see InputSource */ virtual void endInputSource(const InputSource& inputSource); /** Expand a system id * * This method allows an installed XMLEntityHandler to further * process any system id's of enternal entities encountered in * the XML file being parsed, such as redirection etc. * * <b><font color="#FF0000">This method always returns 'false' * for this DOM implementation.</font></b> * * @param systemId A const pointer to an Unicode string representing * the system id scanned by the parser. * @param toFill A pointer to a buffer in which the application * processed system id is stored. * @return 'true', if any processing is done, 'false' otherwise. */ virtual bool expandSystemId ( const XMLCh* const systemId , XMLBuffer& toFill ); /** Reset any entity handler information * * This method allows the installed XMLEntityHandler to reset * itself. * * <b><font color="#FF0000">This method is a no-op for this DOM * implementation.</font></b> */ virtual void resetEntities(); /** Resolve a public/system id * * This method allows a user installed entity handler to further * process any pointers to external entities. The applications can * implement 'redirection' via this callback. This method is also * borrowed from the SAX specification. * * @deprecated This method is no longer called (the other resolveEntity one is). * * @param publicId A const pointer to a Unicode string representing the * public id of the entity just parsed. * @param systemId A const pointer to a Unicode string representing the * system id of the entity just parsed. * @param baseURI A const pointer to a Unicode string representing the * base URI of the entity just parsed, * or <code>null</code> if there is no base URI. * @return The value returned by the user installed resolveEntity * method or NULL otherwise to indicate no processing was done. * The returned InputSource is owned by the parser which is * responsible to clean up the memory. * @see EntityResolver * @see XMLEntityHandler */ virtual InputSource* resolveEntity ( const XMLCh* const publicId , const XMLCh* const systemId , const XMLCh* const baseURI = 0 ); /** Resolve a public/system id * * This method allows a user installed entity handler to further * process any pointers to external entities. The applications can * implement 'redirection' via this callback. * * @param resourceIdentifier An object containing the type of * resource to be resolved and the associated data members * corresponding to this type. * @return The value returned by the user installed resolveEntity * method or NULL otherwise to indicate no processing was done. * The returned InputSource is owned by the parser which is * responsible to clean up the memory. * @see XMLEntityHandler * @see XMLEntityResolver */ virtual InputSource* resolveEntity ( XMLResourceIdentifier* resourceIdentifier ); /** Handle a 'start input source' event * * This method is used to indicate the start of parsing an external * entity file. * * <b><font color="#FF0000">This method is a no-op for this DOM parse * implementation.</font></b> * * @param inputSource A const reference to the InputSource object * which points to the external entity * being parsed. */ virtual void startInputSource(const InputSource& inputSource); //@} // ----------------------------------------------------------------------- // Implementation of the XMLDocumentHandler interface. // ----------------------------------------------------------------------- /** @name Implementation of the XMLDocumentHandler interface. */ //@{ /** Handle document character events * * This method is used to report all the characters scanned by the * parser. This DOM implementation stores this data in the appropriate * DOM node, creating one if necessary. * * @param chars A const pointer to a Unicode string representing the * character data. * @param length The length of the Unicode string returned in 'chars'. * @param cdataSection A flag indicating if the characters represent * content from the CDATA section. */ virtual void docCharacters ( const XMLCh* const chars , const unsigned int length , const bool cdataSection ); /** Handle a document comment event * * This method is used to report any comments scanned by the parser. * A new comment node is created which stores this data. * * @param comment A const pointer to a null terminated Unicode * string representing the comment text. */ virtual void docComment ( const XMLCh* const comment ); /** Handle a document PI event * * This method is used to report any PI scanned by the parser. A new * PI node is created and appended as a child of the current node in * the tree. * * @param target A const pointer to a Unicode string representing the * target of the PI declaration. * @param data A const pointer to a Unicode string representing the * data of the PI declaration. See the PI production rule * in the XML specification for details. */ virtual void docPI ( const XMLCh* const target , const XMLCh* const data ); /** Handle the end of document event * * This method is used to indicate the end of the current document. */ virtual void endDocument(); /** Handle and end of element event * * This method is used to indicate the end tag of an element. The * DOMParse pops the current element off the top of the element * stack, and make it the new current element. * * @param elemDecl A const reference to the object containing element * declaration information. * @param urlId An id referring to the namespace prefix, if * namespaces setting is switched on. * @param isRoot A flag indicating whether this element was the * root element. * @param elemPrefix A const pointer to a Unicode string containing * the namespace prefix for this element. Applicable * only when namespace processing is enabled. */ virtual void endElement ( const XMLElementDecl& elemDecl , const unsigned int urlId , const bool isRoot , const XMLCh* const elemPrefix=0 ); /** Handle and end of entity reference event * * This method is used to indicate that an end of an entity reference * was just scanned. * * @param entDecl A const reference to the object containing the * entity declaration information. */ virtual void endEntityReference ( const XMLEntityDecl& entDecl ); /** Handle an ignorable whitespace vent * * This method is used to report all the whitespace characters, which * are determined to be 'ignorable'. This distinction between characters * is only made, if validation is enabled. * * Any whitespace before content is ignored. If the current node is * already of type DOM_Node::TEXT_NODE, then these whitespaces are * appended, otherwise a new Text node is created which stores this * data. Essentially all contiguous ignorable characters are collected * in one node. * * @param chars A const pointer to a Unicode string representing the * ignorable whitespace character data. * @param length The length of the Unicode string 'chars'. * @param cdataSection A flag indicating if the characters represent * content from the CDATA section. */ virtual void ignorableWhitespace ( const XMLCh* const chars , const unsigned int length , const bool cdataSection ); /** Handle a document reset event * * This method allows the user installed Document Handler to 'reset' * itself, freeing all the memory resources. The scanner calls this * method before starting a new parse event. */ virtual void resetDocument(); /** Handle a start document event * * This method is used to report the start of the parsing process. */ virtual void startDocument(); /** Handle a start element event * * This method is used to report the start of an element. It is * called at the end of the element, by which time all attributes * specified are also parsed. A new DOM Element node is created * along with as many attribute nodes as required. This new element * is added appended as a child of the current node in the tree, and * then replaces it as the current node (if the isEmpty flag is false.) * * @param elemDecl A const reference to the object containing element * declaration information. * @param urlId An id referring to the namespace prefix, if * namespaces setting is switched on. * @param elemPrefix A const pointer to a Unicode string containing * the namespace prefix for this element. Applicable * only when namespace processing is enabled. * @param attrList A const reference to the object containing the * list of attributes just scanned for this element. * @param attrCount A count of number of attributes in the list * specified by the parameter 'attrList'. * @param isEmpty A flag indicating whether this is an empty element * or not. If empty, then no endElement() call will * be made. * @param isRoot A flag indicating whether this element was the * root element. * @see DocumentHandler#startElement */ virtual void startElement ( const XMLElementDecl& elemDecl , const unsigned int urlId , const XMLCh* const elemPrefix , const RefVectorOf<XMLAttr>& attrList , const unsigned int attrCount , const bool isEmpty , const bool isRoot ); /** Handle a start entity reference event * * This method is used to indicate the start of an entity reference. * If the expand entity reference flag is true, then a new * DOM Entity reference node is created. * * @param entDecl A const reference to the object containing the * entity declaration information. */ virtual void startEntityReference ( const XMLEntityDecl& entDecl ); /** Handle an XMLDecl event * * This method is used to report the XML decl scanned by the parser. * Refer to the XML specification to see the meaning of parameters. * * <b><font color="#FF0000">This method is a no-op for this DOM * implementation.</font></b> * * @param versionStr A const pointer to a Unicode string representing * version string value. * @param encodingStr A const pointer to a Unicode string representing * the encoding string value. * @param standaloneStr A const pointer to a Unicode string * representing the standalone string value. * @param actualEncStr A const pointer to a Unicode string * representing the actual encoding string * value. */ virtual void XMLDecl ( const XMLCh* const versionStr , const XMLCh* const encodingStr , const XMLCh* const standaloneStr , const XMLCh* const actualEncStr ); //@} /** @name Deprecated Methods */ //@{ /** Set the 'expand entity references' flag * * DEPRECATED. USE setCreateEntityReferenceNodes instead. * This method allows the user to specify whether the parser should * expand all entity reference nodes. When the 'do expansion' flag is * true, the DOM tree does not have any entity reference nodes. It is * replaced by the sub-tree representing the replacement text of the * entity. When the 'do expansion' flag is false, the DOM tree * contains an extra entity reference node, whose children is the * sub tree of the replacement text. * <p>The default value is 'false'. * * @param expand The new state of the expand entity reference * flag. * @see #setCreateEntityReferenceNodes */ void setExpandEntityReferences(const bool expand); /** Get the 'expand entity references' flag. * DEPRECATED Use getCreateEntityReferenceNodes() instead. * * This method returns the state of the parser's expand entity * references flag. * * @return 'true' if the expand entity reference flag is set on * the parser, 'false' otherwise. * * @see #setExpandEntityReferences * @see #setCreateEntityReferenceNodes * @see #getCreateEntityReferenceNodes */ bool getExpandEntityReferences() const; /** * DEPRECATED Use getValidationScheme() instead * * This method returns the state of the parser's validation * handling flag which controls whether validation checks * are enforced or not. * * @return true, if the parser is currently configured to * do validation, false otherwise. * * @see #setDoValidation * @see #getValidationScheme */ bool getDoValidation() const; /** * DEPRECATED Use setValidationScheme(const ValSchemes newScheme) instead * * This method allows users to enable or disable the parser's validation * checks. * * <p>By default, the parser does not to any validation. The default * value is false.</p> * * @param newState The value specifying whether the parser should * do validity checks or not against the DTD in the * input XML document. * * @see #getDoValidation * @see #setValidationScheme */ void setDoValidation(const bool newState); /** * Deprecated doctypehandler interfaces */ virtual void attDef ( const DTDElementDecl& elemDecl , const DTDAttDef& attDef , const bool ignoring ); virtual void doctypeComment ( const XMLCh* const comment ); virtual void doctypeDecl ( const DTDElementDecl& elemDecl , const XMLCh* const publicId , const XMLCh* const systemId , const bool hasIntSubset , const bool hasExtSubset = false ); virtual void doctypePI ( const XMLCh* const target , const XMLCh* const data ); virtual void doctypeWhitespace ( const XMLCh* const chars , const unsigned int length ); virtual void elementDecl ( const DTDElementDecl& decl , const bool isIgnored ); virtual void endAttList ( const DTDElementDecl& elemDecl ); virtual void endIntSubset(); virtual void endExtSubset(); virtual void entityDecl ( const DTDEntityDecl& entityDecl , const bool isPEDecl , const bool isIgnored ); virtual void resetDocType(); virtual void notationDecl ( const XMLNotationDecl& notDecl , const bool isIgnored ); virtual void startAttList ( const DTDElementDecl& elemDecl ); virtual void startIntSubset(); virtual void startExtSubset(); virtual void TextDecl ( const XMLCh* const versionStr , const XMLCh* const encodingStr ); //@} protected : // ----------------------------------------------------------------------- // Protected getter methods // ----------------------------------------------------------------------- /** @name Protected getter methods */ //@{ /** Get the current DOM node * * This provides derived classes with access to the current node, i.e. * the node to which new nodes are being added. */ DOM_Node getCurrentNode(); //@} // ----------------------------------------------------------------------- // Protected setter methods // ----------------------------------------------------------------------- /** @name Protected setter methods */ //@{ /** Set the current DOM node * * This method sets the current node maintained inside the parser to * the one specified. * * @param toSet The DOM node which will be the current node. */ void setCurrentNode(DOM_Node toSet); /** Set the document node * * This method sets the DOM Document node to the one specified. * * @param toSet The new DOM Document node for this XML document. */ void setDocument(DOM_Document toSet); //@} private : // ----------------------------------------------------------------------- // Protected setter methods // ----------------------------------------------------------------------- void initialize(); void cleanUp(); // unimplemented DOMParser ( const DOMParser& toCopy); DOMParser& operator= (const DOMParser& other); // ----------------------------------------------------------------------- // Private data members // // fCurrentNode // fCurrentParent // Used to track the current node during nested element events. Since // the tree must be built from a set of disjoint callbacks, we need // these to keep up with where we currently are. // // fDocument // The root document object, filled with the document contents. // // fEntityResolver // The installed SAX entity resolver, if any. Null if none. // // fErrorHandler // The installed SAX error handler, if any. Null if none. // // fCreateEntityReferenceNode // Indicates whether entity reference nodes should be created. // // fIncludeIgnorableWhitespace // Indicates whether ignorable whiltespace should be added to // the DOM tree for validating parsers. // // fNodeStack // Used to track previous parent nodes during nested element events. // // fParseInProgress // Used to prevent multiple entrance to the parser while its doing // a parse. // // fScanner // The scanner used for this parser. This is created during the // constructor. // // fWithinElement // A flag to indicate that the parser is within at least one level // of element processing. // // fDocumentType // Used to store and update the documentType variable information // in fDocument // // fToCreateXMLDecTypeNode // A flag to create a DOM_XMLDecl node in the ODM tree if it exists // This is an extension to xerces implementation // // fGrammarPool // The grammar pool passed from external application (through derivatives). // which could be 0, not owned. // // ----------------------------------------------------------------------- bool fToCreateXMLDeclTypeNode; bool fCreateEntityReferenceNodes; bool fIncludeIgnorableWhitespace; bool fParseInProgress; bool fWithinElement; DOM_Node fCurrentParent; DOM_Node fCurrentNode; DOM_Document fDocument; EntityResolver* fEntityResolver; XMLEntityResolver* fXMLEntityResolver; ErrorHandler* fErrorHandler; PSVIHandler* fPSVIHandler; ValueStackOf<DOM_Node>* fNodeStack; XMLScanner* fScanner; DocumentTypeImpl* fDocumentType; GrammarResolver* fGrammarResolver; XMLStringPool* fURIStringPool; XMLValidator* fValidator; MemoryManager* fMemoryManager; XMLGrammarPool* fGrammarPool; }; // --------------------------------------------------------------------------- // DOMParser: Handlers for the XMLEntityHandler interface // --------------------------------------------------------------------------- inline void DOMParser::endInputSource(const InputSource&) { // The DOM entity resolver doesn't handle this } inline bool DOMParser::expandSystemId(const XMLCh* const, XMLBuffer&) { // The DOM entity resolver doesn't handle this return false; } inline void DOMParser::resetEntities() { // Nothing to do on this one } inline void DOMParser::startInputSource(const InputSource&) { // The DOM entity resolver doesn't handle this } // --------------------------------------------------------------------------- // DOMParser: Getter methods // --------------------------------------------------------------------------- inline DOM_Document DOMParser::getDocument() { return fDocument; } inline ErrorHandler* DOMParser::getErrorHandler() { return fErrorHandler; } inline const ErrorHandler* DOMParser::getErrorHandler() const { return fErrorHandler; } inline PSVIHandler* DOMParser::getPSVIHandler() { return fPSVIHandler; } inline const PSVIHandler* DOMParser::getPSVIHandler() const { return fPSVIHandler; } inline EntityResolver* DOMParser::getEntityResolver() { return fEntityResolver; } inline XMLEntityResolver* DOMParser::getXMLEntityResolver() { return fXMLEntityResolver; } inline const XMLEntityResolver* DOMParser::getXMLEntityResolver() const { return fXMLEntityResolver; } inline const EntityResolver* DOMParser::getEntityResolver() const { return fEntityResolver; } inline bool DOMParser::getExpandEntityReferences() const { return !fCreateEntityReferenceNodes; } inline bool DOMParser::getCreateEntityReferenceNodes() const { return fCreateEntityReferenceNodes; } inline bool DOMParser::getIncludeIgnorableWhitespace() const { return fIncludeIgnorableWhitespace; } inline const XMLScanner& DOMParser::getScanner() const { return *fScanner; } inline bool DOMParser::getToCreateXMLDeclTypeNode() const { return fToCreateXMLDeclTypeNode; } // --------------------------------------------------------------------------- // DOMParser: Setter methods // --------------------------------------------------------------------------- inline void DOMParser::setExpandEntityReferences(const bool expand) { fCreateEntityReferenceNodes = !expand; } inline void DOMParser::setCreateEntityReferenceNodes(const bool create) { fCreateEntityReferenceNodes = create; } inline void DOMParser::setIncludeIgnorableWhitespace(const bool include) { fIncludeIgnorableWhitespace = include; } inline void DOMParser::setToCreateXMLDeclTypeNode(const bool create) { fToCreateXMLDeclTypeNode = create; } // --------------------------------------------------------------------------- // DOMParser: Protected getter methods // --------------------------------------------------------------------------- inline DOM_Node DOMParser::getCurrentNode() { return fCurrentNode; } // --------------------------------------------------------------------------- // DOMParser: Protected setter methods // --------------------------------------------------------------------------- inline void DOMParser::setCurrentNode(DOM_Node toSet) { fCurrentNode = toSet; } inline void DOMParser::setDocument(DOM_Document toSet) { fDocument = toSet; } XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 1977 ] ] ]
6a05246aef04c641f414f70658296e66d14bcf76
1142a252973904e5ac5b8b0763af75e42095119b
/PlgnPE/PlgnPE.cpp
081a0d36605723d01f3fa2617b07f9b4ab43ae15
[]
no_license
somma/spinjector
19b57557aefc8556003c779179c76962b62e398a
c9b3634e79ff651b338d6bb718b0fcae2d772dc3
refs/heads/master
2021-01-01T18:17:56.005514
2009-04-20T08:31:13
2009-04-20T08:31:13
32,852,425
0
0
null
null
null
null
UHC
C++
false
false
14,550
cpp
/*----------------------------------------------------------------------------- * PlgnPE.cpp *----------------------------------------------------------------------------- * *----------------------------------------------------------------------------- * All rights reserved by somma ([email protected], [email protected]) *----------------------------------------------------------------------------- * Revision History: * Date Who What * ---------------- ---------------- ---------------- * 28.11.2007 somma birth **---------------------------------------------------------------------------*/ #include "stdafx.h" #include "PlgnPE.h" #include "pe.h" #include "AKUtil.h" #define STRSAFE_NO_DEPRECATE #define STRSAFE_LIB #include <strsafe.h> #pragma comment(lib, "strsafe.lib") /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ #ifdef _MANAGED #pragma managed(push, off) #endif BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { UNREFERENCED_PARAMETER(hModule); UNREFERENCED_PARAMETER(ul_reason_for_call); UNREFERENCED_PARAMETER(lpReserved); switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } return TRUE; } #ifdef _MANAGED #pragma managed(pop) #endif /** --------------------------------------------------------------------------- \brief \param Param->Input.Param_1 : Plugin path ( e.g c:\plgn_pe.dll ) \return Param->Output : PLGN_PE_HANDLE \code \endcode -----------------------------------------------------------------------------*/ PLGNPE_API int __stdcall PlgnInitPlgnPe(PCMD_CALL_PLUGIN_REC Param) { _ASSERTE(NULL != Param); _ASSERTE(TRUE != IsBadWritePtr(Param, sizeof(CMD_CALL_PLUGIN_REC))); if (TRUE == IsBadWritePtr(Param, sizeof(CMD_CALL_PLUGIN_REC))) { return -1; } PLGN_PE_HANDLE p = InitPlgnPe((LPCTSTR) Param->Input.Param_1); if (NULL == p) { return -1; } else { RtlZeroMemory(Param->Output, sizeof(CMD_CALL_PLUGIN_REC)); RtlCopyMemory(Param->Output, &p, sizeof(PLGN_PE_HANDLE)); } return 0; } /** --------------------------------------------------------------------------- \brief \param Param->Input.Param_1 : PLGN_PE_HANDLE \return Param->Output : null \code \endcode -----------------------------------------------------------------------------*/ PLGNPE_API int __stdcall PlgnFreePlgnPe(PCMD_CALL_PLUGIN_REC Param) { _ASSERTE(NULL != Param); _ASSERTE(TRUE != IsBadWritePtr(Param, sizeof(CMD_CALL_PLUGIN_REC))); if (TRUE == IsBadWritePtr(Param, sizeof(CMD_CALL_PLUGIN_REC))) { return -1; } PLGN_PE_HANDLE handle = *(PLGN_PE_HANDLE*)Param->Input.Param_1; FreePlgnPe(handle); RtlZeroMemory(Param->Output, sizeof(CMD_CALL_PLUGIN_REC)); return 0; } /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ PLGNPE_API int __stdcall PlgnGetPluginName(PCMD_CALL_PLUGIN_REC Param) { _ASSERTE(NULL != Param); _ASSERTE(TRUE != IsBadWritePtr(Param, sizeof(CMD_CALL_PLUGIN_REC))); if (TRUE == IsBadWritePtr(Param, sizeof(CMD_CALL_PLUGIN_REC))) { return -1; } if (! SUCCEEDED(StringCbPrintf((LPTSTR)Param->Output, sizeof(Param->Output), _T("%s"), _T("PE analyzer")))) { return -1; } return 0; } /** --------------------------------------------------------------------------- \brief \param Param->Input.Param_1 : PLGN_PE_HANDLE \return Param->Output : PE_HEADER 구조체의 전체 크기 (section 갯수가 PE 마다 다르므로 동적 사이즈임) \return \code \endcode -----------------------------------------------------------------------------*/ PLGNPE_API int __stdcall PlgnGetPEHeaderSize(PCMD_CALL_PLUGIN_REC Param) { _ASSERTE(NULL != Param); _ASSERTE(TRUE != IsBadWritePtr(Param, sizeof(CMD_CALL_PLUGIN_REC))); if (TRUE == IsBadWritePtr(Param, sizeof(CMD_CALL_PLUGIN_REC))) { return -1; } PLGN_PE_HANDLE handle = *(DWORD*)Param->Input.Param_1; DWORD size = GetPEHeaderSize(handle); RtlZeroMemory(Param->Output, sizeof(CMD_CALL_PLUGIN_REC)); RtlCopyMemory(Param->Output, &size, sizeof(DWORD)); return 0; } /** --------------------------------------------------------------------------- \brief \param Param->Input.Param_1 : PLGN_PE_HANDLE \return Param->Output : PE_HEADER 구조체 복사본 (Output 의 정확한 사이즈는 PlgnGetPEHeaderSize() ) \code \endcode -----------------------------------------------------------------------------*/ PLGNPE_API int __stdcall PlgnGetPEHeader(PCMD_CALL_PLUGIN_REC Param) { _ASSERTE(NULL != Param); _ASSERTE(TRUE != IsBadWritePtr(Param, sizeof(CMD_CALL_PLUGIN_REC))); if (TRUE == IsBadWritePtr(Param, sizeof(CMD_CALL_PLUGIN_REC))) { return -1; } PLGN_PE_HANDLE handle = *(PLGN_PE_HANDLE*)Param->Input.Param_1; RtlZeroMemory(Param->Output, sizeof(CMD_CALL_PLUGIN_REC)); int ret = GetPEHeader( handle, sizeof(Param->Output), (PPE_HEADER)Param->Output); return (ret); } /** --------------------------------------------------------------------------- \brief \param Param->Input.Param_1 : PLGN_PE_HANDLE Param->Input.Param_2 : Address to read Param->Input.Param_3 : Length to read \return Param->Output : Address 의 메모리 (Length 만큼) \code \endcode -----------------------------------------------------------------------------*/ PLGNPE_API int __stdcall PlgnReadMemory(PCMD_CALL_PLUGIN_REC Param) { _ASSERTE(NULL != Param); _ASSERTE(TRUE != IsBadWritePtr(Param, sizeof(CMD_CALL_PLUGIN_REC))); if (TRUE == IsBadWritePtr(Param, sizeof(CMD_CALL_PLUGIN_REC))) { return -1; } PLGN_PE_HANDLE handle = *(PLGN_PE_HANDLE*)Param->Input.Param_1; DWORD_PTR Addr = *(DWORD_PTR*)&Param->Input.Param_2; DWORD Len = *(DWORD*)&Param->Input.Param_3; RtlZeroMemory(Param->Output, sizeof(CMD_CALL_PLUGIN_REC)); int ret = ReadMemory(handle, Addr, Len, Param->Output); return (ret); } /** --------------------------------------------------------------------------- \brief \param Param->Input.Param_1 : PLGN_PE_HANDLE Param->Input.Param_2 : Address to write Param->Input.Param_3 : Length to write Param->Input.Param_4 : Data to write \return Param->Output : nil \endcode -----------------------------------------------------------------------------*/ PLGNPE_API int __stdcall PlgnWriteMemory(PCMD_CALL_PLUGIN_REC Param) { _ASSERTE(NULL != Param); _ASSERTE(TRUE != IsBadWritePtr(Param, sizeof(CMD_CALL_PLUGIN_REC))); if (TRUE == IsBadWritePtr(Param, sizeof(CMD_CALL_PLUGIN_REC))) { return -1; } PLGN_PE_HANDLE handle = *(PLGN_PE_HANDLE*)Param->Input.Param_1; DWORD_PTR Addr = *(DWORD_PTR*)&Param->Input.Param_2; DWORD Len = *(DWORD*)&Param->Input.Param_3; PBYTE Buf = (PBYTE) Param->Input.Param_4; int ret = WriteMemory(handle, Addr, Len, Buf); RtlZeroMemory(Param->Output, sizeof(CMD_CALL_PLUGIN_REC)); return (ret); } /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ PLGNPE_API PLGN_PE_HANDLE __stdcall InitPlgnPe(LPCTSTR ImagePath) { PEAnalyzer* p = NULL; if ((NULL == ImagePath) || (0x00 == ImagePath[0])) { // PE image on memory // p = new PEMemory(); if (0 != p->Init()) { delete p; p = NULL; return NULL; } } else { // PE image on file // p = new PEImage(); if (0 != p->Init(ImagePath)) { delete p; p = NULL; return NULL; } } return (PLGN_PE_HANDLE)p; } /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ PLGNPE_API void __stdcall FreePlgnPe(PLGN_PE_HANDLE handle) { _ASSERTE(NULL != handle); if (NULL != handle) { PEAnalyzer* p = (PEAnalyzer*) handle; handle = NULL; delete p; } } /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ PLGNPE_API DWORD __stdcall GetPEHeaderSize(IN PLGN_PE_HANDLE handle) { _ASSERTE(NULL != handle); if (NULL == handle) return 0; PEAnalyzer* pea = (PEAnalyzer*) handle; DWORD ret = pea->GetPEHeaderSize(); return (ret); } /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ PLGNPE_API int __stdcall GetPEHeader( IN PLGN_PE_HANDLE handle, IN DWORD SizeOfDest, OUT PPE_HEADER Dest) { _ASSERTE(NULL != handle); _ASSERTE(NULL != Dest); _ASSERTE(TRUE != IsBadWritePtr(Dest, SizeOfDest)); if ( (NULL == handle) || (NULL == Dest) || (TRUE == IsBadWritePtr(Dest, SizeOfDest)) ) { return -1; } PEAnalyzer* pea = (PEAnalyzer*) handle; if (pea->GetPEHeaderSize() > SizeOfDest) { _ASSERTE(!"too small buffer"); return -1; } int ret = pea->GetPEHeaders(Dest); return (ret); } /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ PLGNPE_API int __stdcall ReadMemory(IN PLGN_PE_HANDLE handle, IN DWORD_PTR Addr, IN DWORD Len, OUT PBYTE Buf) { _ASSERTE(NULL != handle); PEAnalyzer* pea = (PEAnalyzer*) handle; int ret = pea->ReadMemory(Addr, Len, Buf); return (ret); } /** --------------------------------------------------------------------------- \brief \param \return \code \endcode -----------------------------------------------------------------------------*/ PLGNPE_API int __stdcall WriteMemory(IN PLGN_PE_HANDLE handle, IN DWORD_PTR Addr, IN DWORD Len, IN PBYTE Buf) { _ASSERTE(NULL != handle); PEAnalyzer* pea = (PEAnalyzer*) handle; int ret = pea->WriteMemory(Addr, Len, Buf); return (ret); } ///** --------------------------------------------------------------------------- // \brief // // \param // \return // \code // \endcode //-----------------------------------------------------------------------------*/ //PLGNPE_API //PLGN_HKD_HANDLE //__stdcall //PlgnInitHookDefender() //{ // PINTERNAL_HOOK_DEFENDER phkd = (PINTERNAL_HOOK_DEFENDER)malloc(sizeof(INTERNAL_HOOK_DEFENDER)); // if (NULL == phkd) // { // DBG_OP2 _T("insufficient resources") DBG_END // return NULL; // } // RtlZeroMemory(phkd, sizeof(INTERNAL_HOOK_DEFENDER)); // // phkd->rm_hapm = new RM_HAPM; // phkd->rm_rfai = new RM_RFAI; // phkd->hkd = IHKDefender::CreateInstance(); // if ( (NULL == phkd->rm_hapm) || (NULL == phkd->rm_rfai) || // (NULL == phkd->hkd) ) // { // DBG_OP2 _T("insufficient resources") DBG_END // // _free_internal_hook_defender(phkd); // _ASSERTE(NULL == phkd); // // return NULL; // } // // if (0 != phkd->hkd->Init(TRUE, TRUE) ) // { // DBG_OP2 _T("init failed") DBG_END // // _free_internal_hook_defender(phkd); // _ASSERTE(NULL == phkd); // // return NULL; // } // // return (PLGN_HKD_HANDLE) phkd; //} // // // ///** --------------------------------------------------------------------------- // \brief // // \param // \return // \code // \endcode //-----------------------------------------------------------------------------*/ //PLGNPE_API //void //__stdcall //PlgnFreeHookDefender( // PLGN_HKD_HANDLE& handle // ) //{ // _ASSERTE(NULL != handle); // if (NULL != handle) // { // PINTERNAL_HOOK_DEFENDER p = (PINTERNAL_HOOK_DEFENDER) handle; // handle = NULL; // // _free_internal_hook_defender(p); // _ASSERTE(NULL == p); // } //} // ///** --------------------------------------------------------------------------- // \brief // // \param // \return // \code // \endcode //-----------------------------------------------------------------------------*/ //PLGNPE_API //BOOL //__stdcall //PlgnCheckApiHook( // PLGN_HKD_HANDLE& handle // ) //{ // _ASSERTE(NULL != handle); // if (NULL == handle) // { // return FALSE; // } // // PINTERNAL_HOOK_DEFENDER p = (PINTERNAL_HOOK_DEFENDER) handle; // if (0 != p->hkd->CheckApiHook(p->rm_hapm->get())) // { // return FALSE; // } // else // { // return TRUE; // } //} // ///** --------------------------------------------------------------------------- // \brief // // \param // \return // \code // \endcode //-----------------------------------------------------------------------------*/ //PLGNPE_API //BOOL //__stdcall //PlgnRestoreAllApiHook( // PLGN_HKD_HANDLE& handle // ) //{ // _ASSERTE(NULL != handle); // if (NULL == handle) // { // return FALSE; // } // // PINTERNAL_HOOK_DEFENDER p = (PINTERNAL_HOOK_DEFENDER) handle; // if (0 != p->hkd->RestoreApiHook(p->rm_hapm->get(), p->rm_rfai->get())) // { // return FALSE; // } // else // { // return TRUE; // } //} // //#pragma TODO("인덱스를 통해서 한개만 복원할 수 있는 함수 추가")
[ "fixBrain@71c39c02-2d83-11de-bfb9-e98281094dd5" ]
[ [ [ 1, 577 ] ] ]
c5ce79d871f40fda2f61e2b4337477b7a8c59ef3
516b78edbad95d6fb76b6a51c5353eaeb81b56d6
/engine2/src/util/DataManager.h
b1d5e12da48e5808c8c3723715442fccc0698a06
[]
no_license
BackupTheBerlios/lutaprakct
73d9fb2898e0a1a019d8ea7870774dd68778793e
fee62fa093fa560e51a26598619b97926ea9cb6b
refs/heads/master
2021-01-18T14:05:20.313781
2008-06-16T21:51:13
2008-06-16T21:51:13
40,252,766
0
0
null
null
null
null
UTF-8
C++
false
false
993
h
#ifndef DATAMANAGER_H_ #define DATAMANAGER_H_ #include <map> #include <string> #include "../util/Singleton.h" enum{ TextureDataType = 1, MeshDataType }; /*alguns dados so precisam estar 1vez na memoria, como meshes e texturas, * essa classe guarda mantem isso. a struct DataReference conta quantas * vezes um dado foi lido e deletado, so quando chegar a 0 ele eh liberado * da memoria */ struct DataReference{ int counter; void* data; int type; }; /* associa string do filename a ser lido com um ponteiro pro dado */ class DataManager{ public: DataManager(); ~DataManager(); void* loadImage(std::string, int target, int format, int internalformat, int flag); void* loadMesh(std::string); bool unload(std::string filename); bool unloadAll(); private: std::map<std::string, DataReference> data; int textureFlags; }; typedef Singleton<DataManager> DATAMANAGER; #endif /*DATAMANAGER_H_*/
[ "gha" ]
[ [ [ 1, 51 ] ] ]
fa69da2a072db5637b3b8cb4461ef2b6f46ff6d1
b4f709ac9299fe7a1d3fa538eb0714ba4461c027
/trunk/powertabparser.h
456dd262a79e4523a4507df770abf0fc92091d20
[]
no_license
BackupTheBerlios/ptparser-svn
d953f916eba2ae398cc124e6e83f42e5bc4558f0
a18af9c39ed31ef5fd4c5e7b69c3768c5ebb7f0c
refs/heads/master
2020-05-27T12:26:21.811820
2005-11-06T14:23:18
2005-11-06T14:23:18
40,801,514
0
0
null
null
null
null
UTF-8
C++
false
false
1,296
h
///////////////////////////////////////////////////////////////////////////// // Name: powertabparser.h // Purpose: Application for parsing Power Tab files // Author: Brad Larsen // Modified by: // Created: Dec 29, 2004 // RCS-ID: // Copyright: (c) Brad Larsen // License: wxWindows license ///////////////////////////////////////////////////////////////////////////// #ifndef __POWERTABPARSER_H__ #define __POWERTABPARSER_H__ class wxDocManager; class MainFrame; /// Application for parsing Power Tab files class PowerTabParser : public wxApp { protected: wxDocManager* m_docManager; ///< Document manager public: // Constructor/Destructor PowerTabParser(); // Overrides bool OnInit(); int OnExit(); // Document Manager Functions /// Gets a pointer to the document manager /// @return A pointer to the document manager wxDocManager* GetDocManager() const {return (m_docManager);} // Operations protected: void AddDocumentTemplates(); bool LoadXMLResources(); }; DECLARE_APP(PowerTabParser) // Global access to the main frame extern MainFrame* GetMainFrame(); #endif
[ "blarsen@8c24db97-d402-0410-b267-f151a046c31a" ]
[ [ [ 1, 49 ] ] ]
e704d7d615fdcd9645559acf548c8cd15d80954f
2ca3ad74c1b5416b2748353d23710eed63539bb0
/Pilot/CBDTest/CBDTest/stdafx.cpp
51ad0cce33dbef249c75ad6e49af7d69402c4150
[]
no_license
sjp38/lokapala
5ced19e534bd7067aeace0b38ee80b87dfc7faed
dfa51d28845815cfccd39941c802faaec9233a6e
refs/heads/master
2021-01-15T16:10:23.884841
2009-06-03T14:56:50
2009-06-03T14:56:50
32,124,140
0
0
null
null
null
null
UHC
C++
false
false
674
cpp
// stdafx.cpp : source file that includes just the standard includes // CBDTest.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" /**@brief instance들의 초기값을 null로 잡아준다. */ #include "CBFMediator.h" #include "SampleManagerFacade.h" #include "SampleManager2Facade.h" #include "SampleManager2SD.h" //CBFMEdiator CBFMediator *CBFMediator::m_instance = NULL; //Facade SampleManagerFacade *SampleManagerFacade::m_instance = NULL; SampleManager2Facade *SampleManager2Facade::m_instance = NULL; //Service Delegate SampleManager2SD *SampleManager2SD::m_instance = NULL;
[ "nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c" ]
[ [ [ 1, 22 ] ] ]
5a0d70f6a97cd4ca7e1ec6852e575050fa956897
3a79a741fe799d531f363834255d1ce15a520258
/artigos/arquiteturaDeJogos/programacao/animacao/math/Vector3D.h
bb7ef637bb3367f2e894ea2f51b68ec91b40a805
[]
no_license
ViniGodoy/pontov
a8bd3485c53d5fc79312f175610a2962c420c40d
01f8f82209ba10a57d9d220d838cbf00aede4cee
refs/heads/master
2020-04-24T19:33:24.288796
2011-06-20T21:44:03
2011-06-20T21:44:03
32,488,089
0
0
null
null
null
null
IBM852
C++
false
false
10,256
h
/* VinÝcius Godoy de Mendonša */ #ifndef VECTOR3D_H_INCLUDED #define VECTOR3D_H_INCLUDED namespace math { class Vector2D; /** This class represents a 3 coordinate space mathematical vector. All operations expected for a vector, like sum, subtraction, product, cross product, dot product and normalization are provided. The class also provides useful interoperability with Vector2D class. */ class Vector3D { private: float x; float y; float z; public: /** Creates a new null vector 3D */ explicit Vector3D(); /** Create a new vector 3D based on the given values. @param _x x coordinate @param _y y coordinate @param _z z coordinate */ explicit Vector3D(float _x, float _y, float _z); /** Creates a new Vector3D using the x and y coordinates from the given Vector2D and the given z coordinate. @param Vector2D& A 2D vector @param z A z coordinate. */ explicit Vector3D(const Vector2D& other, float _z); /** Creates a new Vector3D using the x and y coordinates from the given Vector2D and applying 0 in the Z coordinate @param Vector2D& A 2D vector */ explicit Vector3D(const Vector2D& other); /** Creates a new Vector3D from the given array. The coordinates will be mapped as following. Index 0 as x, index 1 as y and index 2 as z @param xyz An array containing the x, y, z coordinates */ explicit Vector3D(float xyz[3]); /** @return the X coordinate */ inline float getX() const { return x; } /** @return the Y coordinate */ inline float getY() const { return y; } /** @return the Z coordinate */ inline float getZ() const { return z; } /** Changes the x coordinate. This method was kept void for efficient inlining. @param _x x coordinate. */ inline void setX(float _x) { x = _x; }; /** Changes the y coordinate. This method was kept void for efficient inlining. @param _y y coordinate. */ inline void setY(float _y) { y = _y; }; /** Changes the z coordinate. This method was kept void for efficient inlining. @param _z z coordinate. */ inline void setZ(float _z) { z = _z; }; /** Adds to x coordinate @param _x The amount to add in x @return This vector. */ Vector3D& addX(float _x); /** Adds to y coordinate @param _y The amount to add in y @return This vector. */ Vector3D& addY(float _y); /** Adds to z coordinate @param _z The amount to add in z @return This vector. */ Vector3D& addZ(float _z); /** Adds to all vector coordinates @param _x The amount to add in x @param _y The amount to add in y @param _z The amount to add in z @return This vector. */ Vector3D& add(float _x, float _y, float _z); /** Sets the x, y and z coordinates in one single operation. @param _x The x coordinate @param _y The y coordinate @param _z The z coordinate @return This own vector is returned, for invocation chaning. */ Vector3D& set(float _x, float _y, float _z); /** Sets the x, y and z coordinates in one single operation. The coordinates will be mapped as following. Array index 0 as x, index 1 as y and index 2 as z @param xyz An array containing the x, y, z coordinates @return This own vector is returned, for invocation chaning. */ Vector3D& set(const float xyz[3]); /** Sets the x, y and z coordinates in one single operation. The x and y coordinates will be taken from the given Vector2D. @param Vector2D& A 2D vector @param z A z coordinate. */ Vector3D& set(const Vector2D& v, float _z); /** Allows write access to the vector coordinates as if was an array containing the x in index 0, y in index 1 and z in index 2. No bounds check are made, so be careful. @param k The coordinate index. As descrived above. */ float& operator [](long k); /** Allows read access to the vector coordinates as if was an array containing the x in index 0, y in index 1 and z in index 2. No bounds check are made, so be careful. @param k The coordinate index. As descrived above. */ const float& operator [](long k) const; /** Assigns the value from the other Vector3D in this Vector3D.*/ Vector3D& operator =(const Vector2D& other); /** Assignment operator. z will be assigned to 0. */ Vector3D& operator +=(const Vector3D& other); /** Adds the given Vector3D values to this vector */ Vector3D& operator +=(const Vector2D& other); /** Subtracts this Vector3D from the given vector */ Vector3D& operator -=(const Vector3D& other); /** Subtracts this Vector2D from the given vector. Z coordinate will be left unchanged. */ Vector3D& operator -=(const Vector2D& other); /** Multiplies this vector by the given scalar constant. */ Vector3D& operator *=(float c); /** Divides this vector by the given vector */ Vector3D& operator /=(float c); /** Creates a new Vector that is the negation of this one. */ Vector3D operator -(void) const; /** Creates a new vector with the sum of this and the given one.*/ Vector3D operator +(const Vector3D& other) const; /** Creates a new vector with the sum of this and the given one. The z coordinate will remain equal to this vector z coordinate. */ Vector3D operator +(const Vector2D& other) const; /** Creates a new vector with the subtraction of this and the given one.*/ Vector3D operator -(const Vector3D& other) const; /** Creates a new vector with the subtraction of this and the given one The z coordinate will remain equal to this vector z coordinate. */ Vector3D operator -(const Vector2D& other) const; /** Creates a new vector with the product of this vector and the given scalar constant.*/ Vector3D operator *(float c) const; /** Creates a new vector with the division of this vector and the given scalar constant.*/ Vector3D operator /(float c) const; /** Creates a new vector with the product of this vector and the given one.*/ Vector3D operator *(const Vector3D& other) const; /** Test if two vectors are equal */ bool operator ==(const Vector3D& other) const; /** Test if two vectors are different */ bool operator !=(const Vector3D& other) const; /** @return the size (magnitude) of this vector squared */ float getSizeSqr() const; /** @return the size (magnitude) of this vector */ float getSize() const; /** Sets the size (magnitude) of this vector */ Vector3D& setSize(float size); /** Creates a new vector with the cross product from this vector and the given one. @param other The vector that the cross product will be applyed. @return This own vector is returned, for invocation chaning. */ Vector3D cross(const Vector3D& other) const; /** Apply a cross product in this vector with the given vector. @param other The vector that will be used in the cross product. @return This own vector, modified by the cross product, for invocation chaning. */ Vector3D& applyCross(const Vector3D& other); /** Applies the dot product of this vector and the other one. @return The dot product. */ float dot(const Vector3D& other) const; /** Applies the dot product of this vector and the other one. The z coordinate will be ignored. @return The dot product. */ float dot(const Vector2D& other) const; /** Changes the size of this vector to one. Orientation is left unchanged. */ Vector3D& normalize(void); /** Rotates this vector around the x axis. @return This own vector is returned, for invocation chaning. */ Vector3D& rotateX(float angle); /** Rotates this vector around the y axis. @return This own vector is returned, for invocation chaning. */ Vector3D& rotateY(float angle); /** Rotates this vector around the z axis. @return This own vector is returned, for invocation chaning. */ Vector3D& rotateZ(float angle); /** Rotates this vector around the given axis. @return This own vector is returned, for invocation chaning. */ Vector3D& rotateAxis(float angle, const Vector3D& axis); }; } #endif // VECTOR3D_H_INCLUDED
[ "bcsanches@7ec48984-19c3-11df-a513-1fc609e2573f" ]
[ [ [ 1, 311 ] ] ]
16891e631e14e9828ac7b99abfc5f7a661a8e3fe
9267674a05b4561b921413a711e9dbd6193b936a
/include/skeleton.h
604a8ebbdb5ee58f33bd6ec9b65244ef82504eaa
[]
no_license
scognito/puppetfigher
249564d09eab07f75444dde60fb0f10f6deba2c0
ddf34730304e66dbe8de2d5cd12a5e61f7aded36
refs/heads/master
2021-01-16T23:06:38.792594
2009-09-25T19:56:03
2009-09-25T19:56:03
32,251,497
0
0
null
null
null
null
UTF-8
C++
false
false
2,370
h
#ifndef _SKELETON_H_ #define _SKELETON_H_ #include "bone.h" #include "animation.h" #include <math.h> #include <vector> #include <fat.h> #include <string.h> //#include "Box2D.h" class Skeleton { public: Skeleton(float x, float y, const char* skelFilePath); ~Skeleton(); //Skeleton Absolute Position void SetPosition(float x, float y); //Skeleton Absolute Rotation void SetRotation(float ang); void SetBoneRotation(int boneId, float ang); void SetCurrentAnimation(int anim_id); void SetCurrentAnimation(int anim_id, int nextAnimation); int GetCurrentAnimation(){return _CurrentAnimation;} void StepAnimation(float step_size, float current_step); void SetBoneImage(int boneId, Image* img); void SetBoneImageOffsets(int boneId, float dx, float dy, float dang); int GetBoneId(Armor::Category::Type type, Armor::Side::Type side = Armor::Side::NONE); void Draw(float x_offset, float y_offset); char* GetAnimationNameById(int anim_id); int GetAnimationIdByName(const char* name); float GetX(){return _position_x;} float GetY(){return _position_y;} float GetRotation(){return _rotation;} Sprite* GetBoneSprite(Armor::Category::Type boneType, Armor::Side::Type sideType); bool CollidesWith(Sprite* colSprite, Armor::Category::Type boneType, Armor::Side::Type sideType); //Text debug void Print(); void SetFlip(bool f){_flip = f;} int GetFrameCount(const char* name); void SetAttacking(Armor::Category::Type attackBone); Armor::Category::Type GetAttackBone(){return _attackBone;} bool IsAttacking(){return _isAttacking;} private: void ParseAnimation(std::string file); void ParseSkeleton(std::string file); float CircleDistance(float rot1, float rot2); //variable to store current animation frame int _animationFrame; std::vector<Bone*> _BoneVector; std::vector<Animation::Type> _Animations; Armor::Category::Type _attackBone; bool _isAttacking; int _CurrentAnimation; int _NextAnimation; bool _SingleAnimation; float _position_x; float _position_y; float _rotation; float _x_offset; float _y_offset; bool _flip; //Skelton Physics //b2World *_worldPtr; //b2Body *_body; //LEGS }; #endif //_SKELETON_H_
[ "justin.hawkins@6d35b48c-a465-11de-bea2-1db044c32224" ]
[ [ [ 1, 97 ] ] ]
6c499183b852d8b5cd1377e37080d43cf54c6d01
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit/chromium/public/WebScriptController.h
15f1b3ef2df6aceb24d3f9d660efa95a0232ee9f
[ "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
3,159
h
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef WebScriptController_h #define WebScriptController_h #include "WebCommon.h" namespace v8 { class Extension; } namespace WebKit { class WebString; class WebScriptController { public: // Registers a v8 extension to be available on webpages. The three forms // offer various restrictions on what types of contexts the extension is // loaded into. If a scheme is provided, only pages whose URL has the given // scheme will match. If extensionGroup is provided, the extension will only // be loaded into scripts run via WebFrame::ExecuteInNewWorld with the // matching group. // Will only affect v8 contexts initialized after this call. Takes ownership // of the v8::Extension object passed. WEBKIT_API static void registerExtension(v8::Extension*); WEBKIT_API static void registerExtension(v8::Extension*, const WebString& schemeRestriction); WEBKIT_API static void registerExtension(v8::Extension*, int extensionGroup); // Enables special settings which are only applicable if V8 is executed // in the single thread which must be the main thread. // FIXME: make a try to dynamically detect when this condition is broken // and automatically switch off single thread mode. WEBKIT_API static void enableV8SingleThreadMode(); // Process any pending JavaScript console messages. WEBKIT_API static void flushConsoleMessages(); private: WebScriptController(); }; } // namespace WebKit #endif
[ [ [ 1, 74 ] ] ]
029562e113efe3cd985b80a740ff526887f813e7
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/Tools/libxml/libxml/XMLTreeNode.cpp
70eaf26af2a7f001d164ea40372498be4b7a12dc
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
17,318
cpp
#include "XMLTreeNode.h" #include "Assert.h" //---------------------------------------------------------------------------- // Finalize data //---------------------------------------------------------------------------- void CXMLTreeNode::Done () { if (IsOk()) { Release(); m_bIsOk = false; } } //---------------------------------------------------------------------------- // Free memory //---------------------------------------------------------------------------- void CXMLTreeNode::Release () { if (m_pDoc) { xmlFreeDoc(m_pDoc); m_pDoc = NULL; } m_pNode = NULL; if (m_pWriter) { xmlFreeTextWriter(m_pWriter); m_pWriter = NULL; } xmlCleanupParser(); } //---------------------------------------------------------------------------- // Load File //---------------------------------------------------------------------------- bool CXMLTreeNode::LoadFile (const char* _pszFileName) { m_bIsOk = false; assert(_pszFileName); if (_pszFileName) { m_pDoc = xmlParseFile(_pszFileName); assert(m_pDoc); if (m_pDoc) { m_pNode = xmlDocGetRootElement(m_pDoc); assert(m_pNode); if (m_pNode) { m_bIsOk = true; return true; } } } Release(); return false; } //---------------------------------------------------------------------------- // Returns a subtree node from a given key //---------------------------------------------------------------------------- CXMLTreeNode CXMLTreeNode::GetSubTree (const char* _pszKey) const { assert(m_pNode && _pszKey); CXMLTreeNode NewTree; if (_pszKey && m_pNode) { _FindSubTree(m_pNode, _pszKey, NewTree); } return NewTree; } //---------------------------------------------------------------------------- // Recursive to find a key on a tree //---------------------------------------------------------------------------- bool CXMLTreeNode::_FindSubTree(xmlNodePtr _pNode, const char* _pszKey, CXMLTreeNode& _TreeFound) const { while (_pNode != NULL) { if (xmlStrcmp(_pNode->name, (const xmlChar*)_pszKey)) { if (_FindSubTree(_pNode->xmlChildrenNode, _pszKey, _TreeFound)) { return true; } } else { _TreeFound.m_pNode = _pNode; _TreeFound.m_pDoc = m_pDoc; return true; } _pNode = _pNode->next; } return false; } //---------------------------------------------------------------------------- // Operator that returns a tree node //---------------------------------------------------------------------------- CXMLTreeNode CXMLTreeNode::operator[] (const char* _pszKey) const { assert(_pszKey && m_pNode); CXMLTreeNode TreeFound; if (_pszKey && m_pNode) { TreeFound = GetSubTree(_pszKey); } return TreeFound; } //---------------------------------------------------------------------------- // Operator to get children nodes //---------------------------------------------------------------------------- CXMLTreeNode CXMLTreeNode::operator() (int _iIndex) const { assert(_iIndex >= 0 && m_pNode); CXMLTreeNode TreeFound; if (_iIndex >= 0 && m_pNode) { int iCount = 0; xmlNodePtr pChildren = m_pNode->children; while (pChildren != NULL) { if (_iIndex == iCount) { TreeFound.m_pNode = pChildren; TreeFound.m_pDoc = m_pDoc; break; } pChildren = pChildren->next; ++iCount; } } return TreeFound; } //---------------------------------------------------------------------------- // Returns the number of children a tree has //---------------------------------------------------------------------------- int CXMLTreeNode::GetNumChildren () { assert(m_pNode); int iCount = 0; if (m_pNode) { xmlNodePtr pChildren = m_pNode->children; while (pChildren != NULL) { ++iCount; pChildren = pChildren->next; } } return iCount; } //---------------------------------------------------------------------------- // Returns a param of the tree from a given key //---------------------------------------------------------------------------- xmlChar* CXMLTreeNode::GetProperty (const char* _pszKey) const { assert(_pszKey && m_pNode); xmlChar* value = NULL; if (_pszKey && m_pNode) { value = xmlGetProp(m_pNode, (const xmlChar*)_pszKey); } return value; } //---------------------------------------------------------------------------- // Returns an integer param if found. Else a default value //---------------------------------------------------------------------------- int CXMLTreeNode::GetIntProperty (const char* _pszKey, int _iDefault) const { int iRet = _iDefault; xmlChar* value = GetProperty(_pszKey); if (value) { iRet = atoi((const char*)value); } xmlFree(value); return iRet; } //---------------------------------------------------------------------------- // Returns a float param if found. Else a default value //---------------------------------------------------------------------------- float CXMLTreeNode::GetFloatProperty (const char* _pszKey, float _fDefault) const { float fRet = _fDefault; xmlChar* value = GetProperty(_pszKey); if (value) { fRet = static_cast<float>(atof((const char*)value)); } xmlFree(value); return fRet; } //---------------------------------------------------------------------------- // Returns a boolean param if found. Else a default value //---------------------------------------------------------------------------- bool CXMLTreeNode::GetBoolProperty (const char* _pszKey, bool _bDefault) const { bool bRet = _bDefault; xmlChar* value = GetProperty(_pszKey); if (value) { const char* pszValue = (const char*)value; if (strcmp("TRUE", pszValue) == 0 || strcmp("true", pszValue) == 0 || strcmp("True", pszValue) == 0) { bRet = true; } else bRet = false; } xmlFree(value); return bRet; } //---------------------------------------------------------------------------- // Returns an string param if found. Else a default value //---------------------------------------------------------------------------- const char* CXMLTreeNode::GetPszProperty (const char* _pszKey, const char* _pszDefault) const { const char* pszRet = _pszDefault; xmlChar* value = GetProperty(_pszKey); if (value) { pszRet = (const char*)value; } return pszRet; } //---------------------------------------------------------------------------- // Returns an keyword from the tree from a given key //---------------------------------------------------------------------------- xmlChar* CXMLTreeNode::GetKeyword (const char* _pszKey) const { assert(_pszKey && m_pNode && m_pDoc); xmlChar* value = NULL; if (_pszKey && m_pNode && m_pDoc) { CXMLTreeNode FoundTree; if (_FindSubTree(m_pNode, _pszKey, FoundTree)) value = xmlNodeListGetString(FoundTree.m_pDoc, FoundTree.m_pNode->xmlChildrenNode, 1); } return value; } //---------------------------------------------------------------------------- // Returns an integer keyword if found. Else a default value //---------------------------------------------------------------------------- int CXMLTreeNode::GetIntKeyword (const char* _pszKey, int _iDefault/*=0*/) const { int iRet = _iDefault; xmlChar* value = GetKeyword(_pszKey); if (value) { iRet = atoi((const char*)value); } return iRet; } //---------------------------------------------------------------------------- // Returns a float keyword if found. Else a default value //---------------------------------------------------------------------------- float CXMLTreeNode::GetFloatKeyword (const char* _pszKey, float _fDefault/*=0.0*/) const { float fRet = _fDefault; xmlChar* value = GetKeyword(_pszKey); if (value) { fRet = static_cast<float>(atof((const char*)value)); } return fRet; } //---------------------------------------------------------------------------- // Returns a boolean keyword if found. Else a default value //---------------------------------------------------------------------------- bool CXMLTreeNode::GetBoolKeyword (const char* _pszKey, bool _bDefault/*=false*/) const { bool bRet = _bDefault; xmlChar* value = GetKeyword(_pszKey); if (value) { const char* pszValue = (const char*)value; if (strcmp("TRUE", pszValue) == 0 || strcmp("true", pszValue) == 0 || strcmp("True", pszValue) == 0) { bRet = true; } else bRet = false; } return bRet; } //---------------------------------------------------------------------------- // Returns a string keyword if found. Else a default value //---------------------------------------------------------------------------- const char* CXMLTreeNode::GetPszKeyword (const char* _pszKey, const char* _pszDefault/*=NULL*/) const { const char* pszRet = _pszDefault; xmlChar* value = GetKeyword(_pszKey); if (value) { pszRet = (const char*)value; } return pszRet; } //---------------------------------------------------------------------------- // Checks if a key is on the tree //---------------------------------------------------------------------------- bool CXMLTreeNode::ExistsKey (const char* _pszKey) { assert(_pszKey); CXMLTreeNode TreeFound = GetSubTree(_pszKey); return TreeFound.Exists(); } //---------------------------------------------------------------------------- // Starts a new file and prepares it to be written //---------------------------------------------------------------------------- bool CXMLTreeNode::StartNewFile(const char* _pszFileName) { assert(_pszFileName); m_bIsOk = false; if (_pszFileName) { m_pszFileName = _pszFileName; // Create a new XmlWriter for DOM, with no compression. m_pWriter = xmlNewTextWriterDoc(&m_pDoc, 0); assert(m_pWriter); if (m_pWriter) { // Start the document with the xml default for the version, encoding ISO 8858-1 and the default for the standalone declaration. int rc = xmlTextWriterStartDocument(m_pWriter, NULL, MY_ENCODING, NULL); assert(rc >= 0); if (rc >= 0) { m_bIsOk = true; return true; } } } Release(); return false; } //---------------------------------------------------------------------------- // Finished a file and saves it //---------------------------------------------------------------------------- void CXMLTreeNode::EndNewFile () { assert(m_pWriter && m_pDoc && m_pszFileName); if (m_pWriter && m_pDoc && m_pszFileName) { xmlFreeTextWriter(m_pWriter); m_pWriter = NULL; xmlSaveFileEnc(m_pszFileName, m_pDoc, MY_ENCODING); } } //---------------------------------------------------------------------------- // Write a comment in the xml file in the current node //---------------------------------------------------------------------------- bool CXMLTreeNode::WriteComment(const char* _pszComment) { assert(_pszComment && m_pWriter); if (_pszComment && m_pWriter) { int rc = xmlTextWriterWriteComment(m_pWriter, BAD_CAST _pszComment); assert(rc >= 0); if (rc < 0) return false; } else return false; return true; } //---------------------------------------------------------------------------- // Starts a new node on the tree //---------------------------------------------------------------------------- bool CXMLTreeNode::StartElement(const char* _pszKey) { assert(_pszKey && m_pWriter); if (_pszKey && m_pWriter) { // Start an element named "EXAMPLE". Since thist is the first element, this will be the root element of the document. int rc = xmlTextWriterStartElement(m_pWriter, BAD_CAST _pszKey); assert(rc >= 0); if (rc < 0) return false; } else return false; return true; } //---------------------------------------------------------------------------- // Starts a new node on the tree //---------------------------------------------------------------------------- bool CXMLTreeNode::EndElement() { assert(m_pWriter); if (m_pWriter) { /* Close the element named HEADER. */ int rc = xmlTextWriterEndElement(m_pWriter); assert(rc >= 0); if (rc < 0) return false; } else return false; return true; } //---------------------------------------------------------------------------- // Writes a string keyword //---------------------------------------------------------------------------- bool CXMLTreeNode::WritePszKeyword(const char* _pszKey, const char* _pszValue) { assert(_pszKey && _pszValue && m_pWriter); if (_pszKey && _pszValue && m_pWriter) { // Write an element int rc = xmlTextWriterWriteElement(m_pWriter, BAD_CAST _pszKey, BAD_CAST _pszValue); if (rc >= 0) return true; } return false; } //---------------------------------------------------------------------------- // Writes an integer keyword //---------------------------------------------------------------------------- bool CXMLTreeNode::WriteIntKeyword(const char* _pszKey, int _iValue) { assert(_pszKey && m_pWriter); if (_pszKey && m_pWriter) { char pszValue[32]; sprintf_s(pszValue, "%d", _iValue); // Write an element int rc = xmlTextWriterWriteElement(m_pWriter, BAD_CAST _pszKey, BAD_CAST pszValue); if (rc >= 0) return true; } return false; } //---------------------------------------------------------------------------- // Writes a float keyword //---------------------------------------------------------------------------- bool CXMLTreeNode::WriteFloatKeyword(const char* _pszKey, float _fValue) { assert(_pszKey && m_pWriter); if (_pszKey && m_pWriter) { char pszValue[32]; sprintf_s(pszValue, "%d", _fValue); // Write an element int rc = xmlTextWriterWriteElement(m_pWriter, BAD_CAST _pszKey, BAD_CAST pszValue); if (rc >= 0) return true; } return false; } //---------------------------------------------------------------------------- // Writes a boolean keyword //---------------------------------------------------------------------------- bool CXMLTreeNode::WriteBoolKeyword(const char* _pszKey, bool _bValue) { assert(_pszKey && m_pWriter); if (_pszKey && m_pWriter) { char pszValue[32]; sprintf_s(pszValue, "%d", _bValue ? "true" : "false"); // Write an element int rc = xmlTextWriterWriteElement(m_pWriter, BAD_CAST _pszKey, BAD_CAST pszValue); if (rc >= 0) return true; } return false; } //---------------------------------------------------------------------------- // Writes a string property //---------------------------------------------------------------------------- bool CXMLTreeNode::WritePszProperty(const char* _pszKey, const char* _pszValue) { assert(_pszKey && _pszValue && m_pWriter); if (_pszKey && _pszValue && m_pWriter) { int rc = xmlTextWriterWriteAttribute (m_pWriter, BAD_CAST _pszKey, BAD_CAST _pszValue); if (rc >= 0) return true; } return false; } //---------------------------------------------------------------------------- // Writes an integer property //---------------------------------------------------------------------------- bool CXMLTreeNode::WriteIntProperty(const char* _pszKey, int _iValue) { assert(_pszKey && m_pWriter); if (_pszKey && m_pWriter) { char pszValue[32]; sprintf_s(pszValue, "%d", _iValue); int rc = xmlTextWriterWriteAttribute (m_pWriter, BAD_CAST _pszKey, BAD_CAST pszValue); if (rc >= 0) return true; } return false; } //---------------------------------------------------------------------------- // Writes a float property //---------------------------------------------------------------------------- bool CXMLTreeNode::WriteFloatProperty(const char* _pszKey, float _fValue) { assert(_pszKey && m_pWriter); if (_pszKey && m_pWriter) { char pszValue[32]; sprintf_s(pszValue, "%f", _fValue); int rc = xmlTextWriterWriteAttribute (m_pWriter, BAD_CAST _pszKey, BAD_CAST pszValue); if (rc >= 0) return true; } return false; } //---------------------------------------------------------------------------- // Writes a boolean property //---------------------------------------------------------------------------- bool CXMLTreeNode::WriteBoolProperty(const char* _pszKey, bool _bValue) { assert(_pszKey && m_pWriter); if (_pszKey && m_pWriter) { char pszValue[32]; sprintf_s(pszValue, _bValue ? "true" : "false"); int rc = xmlTextWriterWriteAttribute (m_pWriter, BAD_CAST _pszKey, BAD_CAST pszValue); if (rc >= 0) return true; } return false; }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 656 ] ] ]
2675aded01c5ffa1a2e9db7dddd0607a7db5ade2
58ef4939342d5253f6fcb372c56513055d589eb8
/CloverDemo/source/Tools/src/QueryDlgUtil.cpp
55e1908a9062a21861ecec5783c94ba17911bc8e
[]
no_license
flaithbheartaigh/lemonplayer
2d77869e4cf787acb0aef51341dc784b3cf626ba
ea22bc8679d4431460f714cd3476a32927c7080e
refs/heads/master
2021-01-10T11:29:49.953139
2011-04-25T03:15:18
2011-04-25T03:15:18
50,263,327
0
0
null
null
null
null
GB18030
C++
false
false
5,291
cpp
#include <StringLoader.h> #include <AknQueryDialog.h> #include <AknGlobalNote.h> #include <aknnotewrappers.h> #include <aknmessagequerydialog.h> #include "SHPlatform.h" /********** * * RESOURCE DIALOG r_confirmation_query { flags = EGeneralQueryFlags; buttons = R_AVKON_SOFTKEYS_YES_NO; items = { DLG_LINE { type = EAknCtQuery; id = EGeneralQuery; control = AVKON_CONFIRMATION_QUERY { layout = EConfirmationQueryLayout; label = STRING_r_contacts_con_label_text; }; } }; } RESOURCE DIALOG r_dialog_input { flags = EGeneralQueryFlags; buttons = R_AVKON_SOFTKEYS_OK_CANCEL; items = { DLG_LINE { type = EAknCtQuery; id = EGeneralQuery; control = AVKON_DATA_QUERY { layout = EDataLayout; label = qtn_dialog_url; control = EDWIN { maxlength = 40; }; }; } }; } RESOURCE DIALOG r_about_query_dialog { flags = EGeneralQueryFlags | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow; buttons = R_AVKON_SOFTKEYS_OK_EMPTY; items= { DLG_LINE { type = EAknCtPopupHeadingPane; id = EAknMessageQueryHeaderId; itemflags = EEikDlgItemNonFocusing; control = AVKON_HEADING { }; }, DLG_LINE { type = EAknCtMessageQuery; id = EAknMessageQueryContentId; control = AVKON_MESSAGE_QUERY { }; } }; } * */ TBool ShowConfirmationQueryL( const TInt& aTextResourceId ) { HBufC* prompt = StringLoader::LoadLC( aTextResourceId ); CAknQueryDialog* dlg = CAknQueryDialog::NewL(); dlg->SetPromptL( *prompt ); TInt retCode; // retCode = dlg->ExecuteLD( R_CONFIRMATION_QUERY ) ; CleanupStack::PopAndDestroy(); //prompt return retCode; } TBool ShowConfirmationQueryL( const TDesC& aText ) { CAknQueryDialog* dlg = CAknQueryDialog::NewL(); dlg->SetPromptL( aText ); TInt retCode; // ( dlg->ExecuteLD( R_CONFIRMATION_QUERY ) ); return retCode; } TInt StartWaitingDlg(const TInt& aTextResourceId) { HBufC* prompt = StringLoader::LoadLC( aTextResourceId ); CAknGlobalNote* globalNote = CAknGlobalNote::NewL(); CleanupStack::PushL( globalNote ); TInt noteId = globalNote->ShowNoteL( EAknGlobalWaitNote, prompt->Des() ); CleanupStack::PopAndDestroy(2); return noteId; } void EndWaitingDlg(const TInt& aDlgId) { CAknGlobalNote * note = CAknGlobalNote::NewL(); CleanupStack::PushL( note ); note->CancelNoteL( aDlgId ); CleanupStack::PopAndDestroy(); } void ShowInfomationDlgL(const TInt& aTextResourceId) { HBufC* prompt = StringLoader::LoadLC( aTextResourceId ); CAknInformationNote* iInfoNote = new (ELeave) CAknInformationNote; iInfoNote->ExecuteLD(prompt->Des()); CleanupStack::PopAndDestroy(); } void ShowInfomationDlgL(const TDesC& aDes) { CAknInformationNote* iInfoNote = new (ELeave) CAknInformationNote; iInfoNote->ExecuteLD(aDes); } TBool ShowInputDlgL(const TInt& aTextResourceId,TDes& aText) { HBufC* prompt = StringLoader::LoadLC( aTextResourceId ); CAknTextQueryDialog* dlg = CAknTextQueryDialog::NewL( aText ); dlg->SetPromptL(prompt->Des()); dlg->SetMaxLength(KMaxName); TInt retCode; // ( dlg->ExecuteLD( R_DIALOG_INPUT )); CleanupStack::PopAndDestroy(); //prompt return retCode; } TBool ShowModalInfoDlgL(const TInt& aTextHeaderId,const TDesC& aDes) { HBufC* prompt = StringLoader::LoadLC( aTextHeaderId ); CEikonEnv::Static()->InfoWinL(prompt->Des(),aDes); //任意使用 CleanupStack::PopAndDestroy(); //prompt return ETrue; } TBool ShowModalInfoDlgL(const TInt& aTextHeaderId,const TInt& aTextResourceId) { HBufC* header = StringLoader::LoadLC( aTextHeaderId ); HBufC* prompt = StringLoader::LoadLC( aTextResourceId ); CEikonEnv::Static()->InfoWinL(header->Des(), prompt->Des()); //任意使用 CleanupStack::PopAndDestroy(2); //prompt return ETrue; } TBool ShowModalAboutDlgL(const TInt& aTextHeaderId,const TInt& aTextResourceId) { CAknMessageQueryDialog* dlg = new (ELeave) CAknMessageQueryDialog(); // dlg->PrepareLC(R_ABOUT_QUERY_DIALOG); HBufC* title = StringLoader::LoadLC(aTextHeaderId); dlg->QueryHeading()->SetTextL(*title); CleanupStack::PopAndDestroy(); //title HBufC* msg = StringLoader::LoadLC(aTextResourceId); dlg->SetMessageTextL(*msg); CleanupStack::PopAndDestroy(); //msg dlg->RunLD(); return ETrue; } TBool ShowModalAboutDlgL(const TInt& aTextHeaderId,const TDesC& aDes) { CAknMessageQueryDialog* dlg = new (ELeave) CAknMessageQueryDialog(); // dlg->PrepareLC(R_ABOUT_QUERY_DIALOG); HBufC* title = StringLoader::LoadLC(aTextHeaderId); dlg->QueryHeading()->SetTextL(*title); CleanupStack::PopAndDestroy(); //title dlg->SetMessageTextL(aDes); dlg->RunLD(); return ETrue; }
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 212 ] ] ]
a71349f4ed5a6ca9ced9af4033e229ee6fa01f6e
777399eafeb952743fcb973fbba392842c2e9b14
/CyberneticWarrior/CyberneticWarrior/source/CAtractModeState.h
c50147529828911a620c3ef58f18e47eeef4ab6a
[]
no_license
Warbeleth/cyberneticwarrior
7c0af33ada4d461b90dc843c6a25cd5dc2ba056a
21959c93d638b5bc8a881f75119d33d5708a3ea9
refs/heads/master
2021-01-10T14:31:27.017284
2010-11-23T23:16:28
2010-11-23T23:16:28
53,352,209
0
0
null
null
null
null
UTF-8
C++
false
false
687
h
#ifndef _CATRACTMODESTATE_H_ #define _CATRACTMODESTATE_H_ #include "IGameState.h" class CAtractModeState : public IGameState { float m_fTotalTime; int m_nCurrentImage; // Image Ids int m_nImageIds[3]; // Sound ID int m_nBGMusicId; CAtractModeState( void ); ~CAtractModeState( void ); CAtractModeState(CAtractModeState&); CAtractModeState& operator=(CAtractModeState&); static CAtractModeState* sm_pAtractModeInstance; public: bool Input( void ); void Update( float fElapsedTime ); void Render( void ); void Enter( void ); void Exit( void ); static CAtractModeState* GetInstance( void ); static void DeleteInstance( void ); }; #endif
[ "atmuccio@d49f6b0b-9fae-41b6-31ce-67b77e794db9" ]
[ [ [ 1, 32 ] ] ]
3a3ba6f5419ffd878f6d29a004a0afcdd593ae39
5236606f2e6fb870fa7c41492327f3f8b0fa38dc
/srpc/include/srpc/Exception.h
e231d19dc9f7f628af6abe57629f2dcc7cca78e2
[]
no_license
jcloudpld/srpc
aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88
f2483c8177d03834552053e8ecbe788e15b92ac0
refs/heads/master
2021-01-10T08:54:57.140800
2010-02-08T07:03:00
2010-02-08T07:03:00
44,454,693
0
0
null
null
null
null
UHC
C++
false
false
1,917
h
#ifndef SRPC_EXCEPTION_H #define SRPC_EXCEPTION_H #ifdef _MSC_VER # pragma once #endif #include "srpc.h" #include "utility/CUtils.h" #include <stdexcept> namespace srpc { /** @addtogroup Exception * @{ */ /** * @class Exception * * root runtime_error class. */ class SRPC_API_INLINE Exception : public std::runtime_error { enum { MAX_BUFFER_SIZE = 512 }; public: Exception(const char* file, int fileno, const char* msg) : std::runtime_error("") { #ifdef _MSC_VER # pragma warning (push) # pragma warning (disable: 4996) #endif snprintf(what_, MAX_BUFFER_SIZE - 1, "Exception: (%s:%d), %s", file, fileno, msg); #ifdef _MSC_VER # pragma warning (pop) #endif } virtual const char* what() const throw() { return what_; } private: char what_[MAX_BUFFER_SIZE]; }; /** * @class StreamingException * * 스트리밍(marshaling/unmarshaling) 에러 */ class SRPC_API_INLINE StreamingException : public Exception { public: StreamingException(const char* file, int fileno, const char* what) : Exception(file, fileno, what) {} }; /** * @class UnknownRpcMethodException * * 알 수 없는 RPC 요청을 수신한 경우 */ class SRPC_API_INLINE UnknownRpcMethodException : public Exception { public: UnknownRpcMethodException(const char* file, int fileno, const char* what) : Exception(file, fileno, what) {} }; /** * @class RpcFailedException * * RPC 요청을 처리하는 도중 에러가 발생할 경우 * - 접속을 해제해야 할 경우 throw. */ class SRPC_API_INLINE RpcFailedException : public Exception { public: RpcFailedException(const char* file, int fileno, const char* what) : Exception(file, fileno, what) {} }; /** @} */ // addtogroup Exception } // namespace srpc #endif // SRPC_EXCEPTION_H
[ "kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4" ]
[ [ [ 1, 91 ] ] ]
c52b7931fbd3b92ec02abc49afd8fff4568c68bd
19b8f2132768c8c52238180e15815cbd4243b41d
/EDA fase II/EDA II Fase 11000/Bee/main.cpp
958bdfdf5235b926450f2618203ad94c2282404f
[]
no_license
Greatfox/Programas-EDA
604ae99e2576ecfae8a0a2965834d1206f41fb02
73d5d5961e041c27aadea0314f066e21e6d87807
refs/heads/master
2016-09-03T02:23:10.221535
2011-12-16T04:44:39
2011-12-16T04:44:39
2,279,239
0
0
null
null
null
null
UTF-8
C++
false
false
915
cpp
#include <iostream> #include <cstdio> #include <string> #include <vector> #include <sstream> #include <math.h> using namespace std; unsigned long fibonacci( unsigned long number ) { if ( ( number == 0 ) || ( number == 1 ) ) return number; else return fibonacci( number - 1 ) + fibonacci( number - 2 ); } /*int fibonacci(int n) { int fibminus2=0; int fibminus1=1; int fib=0; int i; if (n==0 || n==1) return n; for(i=2;i<=n;i++){ fib=fibminus1+fibminus2; fibminus2=fibminus1; fibminus1=fib; } return fib; } */ int main() { int N; while(cin) { cin>>N; if(N==-1) {break;} int AM=0; int AT=0; int AF=0; for(int i=1;i<=N;i++) { AF=fibonacci(2+(i-1)); if(AT==0) {AM=AT+1;} else {AM=AT;} AT=AM+AF; } cout<<AM<<" "<<AT<<endl; } }
[ [ [ 1, 61 ] ] ]
260d05c9e52b9170799751bc0e609677d213dfeb
d54914353e2234161c29c83b41c1097e3a11c0b7
/ talapatram --username ramavorray/Talapatram.cpp
7aaa8d82ee7ca1120ef4645f8a27ad4b66732a71
[]
no_license
ramavorray/talapatram
0f8d81fbe90b2573bd21d030aa62eeec4c8461bc
c7631988b4ccd8a6a12261136af1985432cd38e7
refs/heads/master
2016-09-06T00:41:44.288127
2009-03-30T21:46:26
2009-03-30T21:46:26
32,348,799
0
0
null
null
null
null
UTF-8
C++
false
false
3,671
cpp
// Talapatram.cpp : Defines the class behaviors for the application. #include "stdafx.h" #include "Talapatram.h" #include "TalapatramDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CTalapatramApp BEGIN_MESSAGE_MAP(CTalapatramApp, CWinApp) ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() CTalapatramApp::CTalapatramApp() { // Place all significant initialization in InitInstance } // The one and only CTalapatramApp object CTalapatramApp theApp; /** * CTalapatramApp initialization. License-check is also done here. */ BOOL CTalapatramApp::InitInstance() { // InitCommonControls() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. InitCommonControls(); CWinApp::InitInstance(); AfxEnableControlContainer(); FILE *fp; if(_wfopen_s(&fp, _T("LICENSE-DONT-DELETE.txt"), _T("rb")) != 0) { MessageBox(NULL, _T("Oi... Your License file is missing! Contact me at www.funnotes.net/talapatram/contact.html with details."), _T("License Error"), MB_OK); return -1; } unsigned int licsNum=0; fread(&licsNum, sizeof(unsigned int), 1, fp); //license number is 673673688 //just an arbitrary number that is written in binary mode into a text file called 'LICENSE-DONT-DELETE.txt' //this file will be hidden in the folder where executable file is there. if(licsNum!=673673688) { fclose(fp); MessageBox(NULL, _T("Ppcch... It seems you messed up my License? Contact me at www.funnotes.net/talapatram/contact.html with details."), _T("License Error"), MB_OK); return -1; } else fclose(fp); //resolution should be 1152 width and 768 height minimum if(GetSystemMetrics(SM_CXSCREEN)<1152 || GetSystemMetrics(SM_CYSCREEN)<768) { if(MessageBox(NULL, _T("I need display resolution of atleast 1152 X 768. Shall I try changing your Display Resolution?"), _T("Settings not compatible"), MB_YESNO)==IDYES) { DEVMODE dispMode; EnumDisplaySettings(NULL, ENUM_REGISTRY_SETTINGS, &dispMode); dispMode.dmPelsWidth=1152; dispMode.dmPelsHeight=768; dispMode.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT; if(ChangeDisplaySettings(&dispMode, CDS_UPDATEREGISTRY)!=DISP_CHANGE_SUCCESSFUL) MessageBox(NULL, _T("Sorry... It has not been possible for me to change your display resolution. Your display resolution should be atleast 1152 pixels wide and 768 pixels high. Please change settings manually."), _T("Please change settings"), MB_OK); } } /*----------------------------- Standard initialization If you are not using these features and wish to reduce the size of your final executable, you should remove from the following the specific initialization routines you do not need. Change the registry key under which our settings are stored TODO: You should modify this string to be something appropriate such as the name of your company or organization. THIS REGISTRY NAME SHOULD NOT BE CHANGED BY ANYONE. DOING SO WILL BE VIOLATION OF MY T&Cs. -----------------------------*/ SetRegistryKey(_T("Talapatram, Vorray Inc.")); CTalapatramDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { //Place code here to handle when the dialog is //dismissed with OK } else if (nResponse == IDCANCEL) { //Place code here to handle when the dialog is //dismissed with Cancel } //Since the dialog has been closed, return FALSE so that we exit the //application, rather than start the application's message pump. return FALSE; }
[ "ramavorray@1e59233a-b841-0410-9934-83d5419519a6" ]
[ [ [ 1, 109 ] ] ]
f4bfc37fc7e4522d91c7d401d565d49964328670
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nscene/src/nscene/nblendshapenode_main.cc
9aa4195b1eb5a3ea0aefe2be68ce045ad710060b
[]
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
9,354
cc
#include "precompiled/pchnscene.h" //------------------------------------------------------------------------------ // nblendshapenode_main.cc // (C) 2004 RadonLabs GmbH //------------------------------------------------------------------------------ #include "nscene/nblendshapenode.h" #include "gfx2/nmesh2.h" nNebulaScriptClass(nBlendShapeNode, "ngeometrynode"); //------------------------------------------------------------------------------ /** */ nBlendShapeNode::nBlendShapeNode() : totalNumTargets(0), activeTargets(0), numShapes(0), groupIndex(0), shapeArray(MaxShapes) { // empty } //------------------------------------------------------------------------------ /** */ nBlendShapeNode::~nBlendShapeNode() { // empty } //------------------------------------------------------------------------------ /** This method must return the mesh usage flag combination required by this shape node class. Subclasses should override this method based on their requirements. @return a combination on nMesh2::Usage flags */ int nBlendShapeNode::GetMeshUsage() const { return nMesh2::WriteOnce | nMesh2::NeedsVertexShader; } //------------------------------------------------------------------------------ /** Load the resources needed by this object. */ bool nBlendShapeNode::LoadResources() { nGeometryNode::LoadResources(); if(!this->refFullMeshArray.isvalid()) { this->refFullMeshArray = nGfxServer2::Instance()->NewMeshArray(0); } // update resouce filenames in mesharray int i; for (i = 0; i < this->totalNumTargets; i++) { this->refFullMeshArray->SetFilenameAt(i, this->shapeArray[i].meshName); this->refFullMeshArray->SetUsageAt(i, this->GetMeshUsage()); } this->resourcesValid &= this->refFullMeshArray->Load(); // update shape bounding boxes if (true == this->resourcesValid) { for(i = 0; i < this->totalNumTargets; i++) { nMesh2* mesh = this->refFullMeshArray->GetMeshAt(i); if (0 != mesh) { this->shapeArray[i].localBox = mesh->Group(this->groupIndex).GetBoundingBox(); } } } return this->resourcesValid; } //------------------------------------------------------------------------------ /** Unload the resources. */ void nBlendShapeNode::UnloadResources() { nGeometryNode::UnloadResources(); if (this->refFullMeshArray.isvalid()) { this->refFullMeshArray->Unload(); this->refFullMeshArray->Release(); this->refFullMeshArray.invalidate(); } } //------------------------------------------------------------------------------ /** Set the mesh resource name at index. Updates the number of current valid shapes. @param index @param name name of the resource to set, 0 to unset a resource */ void nBlendShapeNode::SetMeshAt(int index, const char* name) { n_assert((index >= 0) && (index < MaxShapes)); if (this->shapeArray[index].meshName != name) { this->resourcesValid = false; this->shapeArray[index].meshName = name; //<OBSOLETE> if (0 != name) { // increase shapes count this->numShapes = n_max(index+1, this->numShapes); } else { // decrease shapes count if this was the last element if (index + 1 == this->numShapes) { this->numShapes--; } } //</OBSOLETE> this->totalNumTargets++; if( this->totalNumTargets < MaxShapes ) { this->activeTargets = this->totalNumTargets; } } } //------------------------------------------------------------------------------ /** Gives the weights to the shader */ bool nBlendShapeNode::ApplyShader(nSceneGraph* /*sceneGraph*/) { return true; } //------------------------------------------------------------------------------ /** Perform pre-instancing actions needed for rendering geometry. This is called once before multiple instances of this shape node are actually rendered. */ bool nBlendShapeNode::Apply(nSceneGraph* sceneGraph) { if (nGeometryNode::Apply(sceneGraph)) { return true; } return false; } //------------------------------------------------------------------------------ /** Update geometry, set as current mesh in the gfx server and call nGfxServer2::DrawIndexed(). - 15-Jan-04 floh AreResourcesValid()/LoadResource() moved to scene server */ bool nBlendShapeNode::Render(nSceneGraph* sceneGraph, nEntityObject* entityObject) { nGeometryNode::Render(sceneGraph, entityObject); /// get mesharray data ncScene *renderContext = entityObject->GetComponent<ncScene>(); nVariable var; var = renderContext->GetLocalVar(this->meshArrayIndex); // set mesh, vertex and index range nMeshArray* meshArray = static_cast<nMeshArray*>(var.GetObj()); nGfxServer2::Instance()->SetMeshArray(meshArray); const nMeshGroup& curGroup = meshArray->GetMeshAt(0)->Group(this->groupIndex); nGfxServer2::Instance()->SetVertexRange(curGroup.GetFirstVertex(), curGroup.GetNumVertices()); nGfxServer2::Instance()->SetIndexRange(curGroup.GetFirstIndex(), curGroup.GetNumIndices()); // Weights must be rendered here to allow overriding from animators // FIXME move to nSurfaceNode::Apply for blending surfaces, like swing surfaces. nShader2* shader = nGfxServer2::Instance()->GetShader(); n_assert(shader); //int numShapes = this->GetNumShapes(); int numShapes = this->GetNumActiveTargets(); if (shader->IsParameterUsed(nShaderState::VertexStreams)) { shader->SetInt(nShaderState::VertexStreams, numShapes); } if (numShapes > 0) { if (shader->IsParameterUsed(nShaderState::VertexWeights1)) { nFloat4 weights = {0.0f, 0.0f, 0.0f, 0.0f}; if (numShapes > 0) weights.x = this->GetWeightAt(0); if (numShapes > 1) weights.y = this->GetWeightAt(1); if (numShapes > 2) weights.z = this->GetWeightAt(2); if (numShapes > 3) weights.w = this->GetWeightAt(3); shader->SetFloat4(nShaderState::VertexWeights1, weights); } } if (numShapes > 4) { if (shader->IsParameterUsed(nShaderState::VertexWeights2)) { nFloat4 weights = {0.0f, 0.0f, 0.0f, 0.0f}; if (numShapes > 4) weights.x = this->GetWeightAt(4); if (numShapes > 5) weights.y = this->GetWeightAt(5); if (numShapes > 6) weights.z = this->GetWeightAt(6); if (numShapes > 7) weights.w = this->GetWeightAt(7); shader->SetFloat4(nShaderState::VertexWeights2, weights); } } nGfxServer2::Instance()->DrawIndexedNS(nGfxServer2::TriangleList); return true; } //------------------------------------------------------------------------------ /** */ void nBlendShapeNode::FillInstantMeshArray( nEntityObject* entityObject, nArray<int>& curveIndices, nArray<int>& targetIndices) { ncScene *renderContext = entityObject->GetComponent<ncScene>(); nVariable var; var = renderContext->GetLocalVar(this->meshArrayIndex); nMeshArray* meshArray = static_cast<nMeshArray*>(var.GetObj()); meshArray->Unload(); // change targets for (int i = 0; i < targetIndices.Size() ; i++) { meshArray->SetFilenameAt(curveIndices[i], this->shapeArray[ targetIndices[i] ].meshName); meshArray->SetUsageAt(curveIndices[i], this->GetMeshUsage()); } meshArray->Load(); } //------------------------------------------------------------------------------ /** */ void nBlendShapeNode::EntityCreated(nEntityObject* entityObject) { ncScene *renderContext = entityObject->GetComponent<ncScene>(); // see if resources need to be reloaded if (!this->AreResourcesValid()) { this->LoadResources(); } nMeshArray* refMeshArray; refMeshArray = nGfxServer2::Instance()->NewMeshArray(0); // fill for first time with all targets REMOVE IT??? DO NOT REMOVE, useful for deformeranimator int i; for (i = 0; i < this->totalNumTargets; i++) { refMeshArray->SetFilenameAt(i, this->shapeArray[i].meshName); refMeshArray->SetUsageAt(i, this->GetMeshUsage()); } refMeshArray->Load(); // put mesharray in render context this->meshArrayIndex = renderContext->AddLocalVar(nVariable(0, refMeshArray)); } //------------------------------------------------------------------------------ /** */ void nBlendShapeNode::EntityDestroyed(nEntityObject* entityObject) { ncScene *renderContext = entityObject->GetComponent<ncScene>(); nVariable var; var = renderContext->GetLocalVar(this->meshArrayIndex); nMeshArray* meshArray = static_cast<nMeshArray*>(var.GetObj()); n_assert(meshArray); n_delete(meshArray); }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 305 ] ] ]
d463fade73d66c9d797e1233e06804ab7fe7d682
4a497fe12f03275fbae727063dbcd027280bca13
/Source/itkBinaryHysteresisThresoldImageFilter.h
f259306d41ade3ba3f054ae9e0cd1877b05fc5af
[]
no_license
midas-journal/midas-journal-847
da7c9cade098abe6e805e3431a748d020f01469a
cb4e44e1bc938e41a0c7e08492c4c5cb1030d059
refs/heads/master
2021-01-19T15:31:49.453266
2011-12-19T13:59:02
2011-12-19T13:59:02
3,012,288
0
0
null
null
null
null
UTF-8
C++
false
false
5,125
h
#ifndef _itkBinaryHysteresisThresoldImageFilter_h #define _itkBinaryHysteresisThresoldImageFilter_h #include <ctime> #include <list> #include <itkImage.h> #include <itkNeighborhoodIterator.h> #include <itkImageRegionIterator.h> #include <itkConstantBoundaryCondition.h> #include <itkImageToImageFilter.h> namespace itk { /// \brief Computation of Binary thresholding with hysteresis /// /// Any pixels aveve highThreshold are set to Inside Value. Pixels /// below lowerThreshold are set to Outside Value. voxels between /// low and high tresholds will be set to Inside value if they are connected to /// any voxel with value Inside. /// TODO: /// 1. manual instantation template<class TInputImage, class TOutputPixelType = unsigned char> class ITK_EXPORT BinaryHysteresisThresoldImageFilter : public ImageToImageFilter< TInputImage, ::itk::Image< TOutputPixelType,::itk::GetImageDimension<TInputImage>::ImageDimension> > { public: //----------------------------------------------------- // Typedefs //----------------------------------------------------- typedef typename itk::Image< TOutputPixelType, TInputImage::ImageDimension> TOutputImage; /** Standard class typedefs. */ typedef BinaryHysteresisThresoldImageFilter Self; typedef ImageToImageFilter<TInputImage, TOutputImage> Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(BinaryHysteresisThresoldImageFilter, ImageToImageFilter); typedef itk::ConstantBoundaryCondition< TOutputImage > OutputBCType; typedef typename TInputImage::ConstPointer InputConstPointerType; typedef typename TOutputImage::Pointer OutputPointerType; typedef typename TOutputImage::IndexType OutputIndexType; typedef typename TOutputImage::SizeType OutputSizeType; typedef typename TOutputImage::RegionType OutputRegionType; typedef typename TOutputImage::PixelType OutputPixelType; typedef typename TInputImage::IndexType InputIndexType; typedef typename TInputImage::PixelType InputPixelType; typedef itk::ImageRegionConstIterator< TInputImage > InputConstIteratorType; typedef itk::ImageRegionIterator< TOutputImage > OutputIteratorType; typedef itk::ConstNeighborhoodIterator< TInputImage > InputConstNeighborhoodIteratorType; typedef itk::NeighborhoodIterator< TOutputImage > OutputNeighborhoodIteratorType; /** The dimension of the input and output images. */ itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); itkStaticConstMacro(OutputImageDimension, unsigned int, TOutputImage::ImageDimension); //----------------------------------------------------- // Methods //----------------------------------------------------- /** Set the lower threshold. */ itkSetMacro(LowerThreshold, InputPixelType); /** Get the upper threshold . */ itkGetConstReferenceMacro(LowerThreshold, InputPixelType); /** Set the upper threshold. */ itkSetMacro(UpperThreshold, InputPixelType); /** Get the upper threshold . */ itkGetConstReferenceMacro(UpperThreshold, InputPixelType); /** Set the upper threshold. */ itkSetMacro(InsideValue, OutputPixelType); /** Get the upper threshold . */ itkGetConstReferenceMacro(InsideValue, OutputPixelType); /** Set the upper threshold. */ itkSetMacro(OutsideValue, OutputPixelType); /** Get the upper threshold . */ itkGetConstReferenceMacro(OutsideValue, OutputPixelType); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(SameDimensionCheck, (Concept::SameDimension<InputImageDimension, OutputImageDimension>)); /** End concept checking */ #endif protected: /// \brief Default Constructor BinaryHysteresisThresoldImageFilter(); /// \brief Destructor virtual ~BinaryHysteresisThresoldImageFilter(); /** Compute the medial Surface. */ void GenerateData(); void PrintSelf(std::ostream& os, Indent indent) const; //----------------------------------------------------- // Variables //----------------------------------------------------- InputPixelType m_LowerThreshold; // Lower Threshold InputPixelType m_UpperThreshold; // Upper Threshold OutputPixelType m_InsideValue; // Inside Value OutputPixelType m_OutsideValue; // Inside Value InputConstPointerType m_inputImg; OutputPointerType m_outputImg; OutputPointerType m_queueImg; OutputRegionType m_region; std::list<OutputIndexType> m_nodeList; }; #include "itkBinaryHysteresisThresoldImageFilter.txx" }//end itk namespace #endif // _itkBinaryHysteresisThresoldImageFilter_h
[ [ [ 1, 146 ] ] ]
7ab1a05b425b1b86ac8fd50d19327e38e6c8c779
698f3c3f0e590424f194a4c138ed9706eb28b34f
/Classes/Board.cpp
6e7dc43387cb6fd7ddafd048d7463752f096b4c5
[]
no_license
nghepop/super-fashion-puzzle-cocos2d-x
16b3a86072a6758fc2547b9e177bbfeebed82681
5e8d8637e3cf70b4ec45256347ccf7b350c11bce
refs/heads/master
2021-01-10T06:28:10.028735
2011-12-03T23:49:16
2011-12-03T23:49:16
44,685,435
0
0
null
null
null
null
UTF-8
C++
false
false
8,168
cpp
#include "Board.h" Board::Board(void) { } Board::~Board(void) { } // init when a game is restored from a saved file Board* Board::initWithPlayingScene(PlayingScene* playingScene) { // if( (self=[super init] )) { // board background texture CCSprite* board_sprite = CCSprite::spriteWithFile("game/board.png"); addChild(board_sprite); // board rect m_boardRect = board_sprite->getTextureRect(); // calculate board size CCSize s = board_sprite->getContentSize(); m_boardRect = CCRectMake(-s.width / 2, -s.height / 2, s.width, s.height); // pieces texture m_piecesSpriteSheetTexture = CCTextureCache::sharedTextureCache()->addImage("game/pieces.pvr"); CCSpriteFrameCache* spriteFrameCache = CCSpriteFrameCache::sharedSpriteFrameCache(); spriteFrameCache->addSpriteFramesWithFile("game/pieces.plist", m_piecesSpriteSheetTexture); // create 10*5 instances of Piece class m_piecesDataBase = new CCMutableArray<CCObject *>(50); for (unsigned int girl = 0; girl < NUMBER_OF_GIRLS; girl++) { CCMutableArray<CCObject *> *pieces = new CCMutableArray<CCObject *>(NUMBER_OF_PIECES_PER_GIRL); for (unsigned int piece = 0; piece < NUMBER_OF_PIECES_PER_GIRL; piece++) { // texture filename and path char originalTextureFilename[256] = {0}; sprintf(originalTextureFilename,"g%d_f%d.png", girl+1, piece+1); CCSpriteFrame* spriteFrame = spriteFrameCache->spriteFrameByName(originalTextureFilename); //Piece* pieceInstance=[[Piece alloc] initNormalPieceWithSpriteFrame:spriteFrame Piece:piece Girl:girl]; // Piece* pieceInstance = new Piece::initNormalPieceWithSpriteFrame(spriteFrame, piece, girl); Piece* pieceInstance = new Piece(); pieceInstance->initNormalPieceWithSpriteFrame(spriteFrame, piece, girl); pieces->addObject(pieceInstance); pieceInstance->release(); } m_piecesDataBase->addObject(pieces); pieces->release(); } // wildcard piece CCSpriteFrame* wildcardSpriteFrame = spriteFrameCache->spriteFrameByName("wildcard.png"); CCAssert(wildcardSpriteFrame != NULL, "wildcardSpriteFrame cannot be null."); // m_wildcardPiece= [[Piece alloc] initWildcardWithSpriteFrame:wildcardSpriteFrame]; Piece * pieceInstance = new Piece(); pieceInstance->initWildcardWithSpriteFrame(wildcardSpriteFrame); pieceInstance->release(); // used by BoardPiecePlace when any of them is selected with m_selectedAction m_selectedTexture = CCTextureCache::sharedTextureCache()->addImage("game/selection_animated_0001.png"); // used by BoardPiecePlace when any of them is selected with m_selectedSprite //CCAnimation* selectedAnimation=CCAnimation animationWithName:"selectedAnimation" delay:1/12.0f]; CCAnimation* selectedAnimation = CCAnimation::animation(); selectedAnimation->setDelay(1/12.0f); for (unsigned int i=1; i <= 11; i++) { char originalTextureFilename[256] = {0}; sprintf(originalTextureFilename,"game/selection_animated_%04d.png", i); selectedAnimation->addFrameWithFileName(originalTextureFilename); } // create an animation/action and add it to action container CCAnimate* selectedAnimationAction = CCAnimate::actionWithAnimation(selectedAnimation); m_selectedAction = CCRepeatForever::actionWithAction(selectedAnimationAction); m_selectedAction->retain(); // matching starting sequence, used by BoardPiecePlace // CCAnimation* startingMatchingAnimation = CCAnimation::animationWithName("startingMatchingAnimation" delay:1/12.0f); CCAnimation* startingMatchingAnimation = CCAnimation::animation(); startingMatchingAnimation->setDelay(1/12.0f); for (unsigned int i=1; i<=5; i++) { char originalTextureFilename[256] = {0}; sprintf(originalTextureFilename,"game/starting_matching_sequence_%04d.png", i); startingMatchingAnimation->addFrameWithFileName(originalTextureFilename); } m_startingMatchingAction = CCAnimate::actionWithAnimation(startingMatchingAnimation); m_startingMatchingAction->retain(); // correct matching ending sequence, used by BoardPiecePlace //CCAnimation* correctMatchingEndingAnimation=[CCAnimation animationWithName:@"correctMatchingEndingAnimation" delay:1/12.0f]; CCAnimation* correctMatchingEndingAnimation = CCAnimation::animation(); correctMatchingEndingAnimation->setDelay(1/12.0f); for (unsigned int i=6; i<=11; i++) { //NSString* originalTextureFilename=[NSString stringWithFormat:@"correct_matching_ending_sequence_%04d.png", i]; //[correctMatchingEndingAnimation addFrameWithFilename:originalTextureFilename]; char originalTextureFilename[256] = {0}; sprintf(originalTextureFilename,"game/correct_matching_ending_sequence_%04d.png", i); correctMatchingEndingAnimation->addFrameWithFileName(originalTextureFilename); } m_correctMatchingEndingAction = CCAnimate::actionWithAnimation(correctMatchingEndingAnimation); m_correctMatchingEndingAction->retain(); // incorrect matching ending sequence, used by BoardPiecePlace // CCAnimation* incorrectMatchingEndingAnimation=[CCAnimation animationWithName:@"incorrectMatchingEndingAnimation" delay:1/12.0f]; CCAnimation* incorrectMatchingEndingAnimation = CCAnimation::animation(); incorrectMatchingEndingAnimation->setDelay(1/12.0f); for (unsigned int i=6; i<=11; i++) { //NSString* originalTextureFilename=[NSString stringWithFormat:@"incorrect_matching_ending_sequence_%04d.png", i]; //[incorrectMatchingEndingAnimation addFrameWithFilename:originalTextureFilename]; char originalTextureFilename[256] = {0}; sprintf(originalTextureFilename,"game/incorrect_matching_ending_sequence_%04d.png", i); incorrectMatchingEndingAnimation->addFrameWithFileName(originalTextureFilename); } m_incorrectMatchingEndingAction = CCAnimate::actionWithAnimation(incorrectMatchingEndingAnimation); m_incorrectMatchingEndingAction->retain(); // starting matching texture, used by BoardPiecePlace m_startingMatchingTexture=CCTextureCache::sharedTextureCache()->addImage("game/starting_matching_sequence_0001.png"); #if 0 // pivot node for BoardPiecePlace m_boardPiecePlacesPivotNode = BoardPiecePlacesPivotNode::node(); m_boardPiecePlacesPivotNode->retain(); this->addChild(m_boardPiecePlacesPivotNode); #endif // add 7*7 BoardPiecePlace, each one has a node, and this node is also taken by Board // each one with a nodes with their position offsets to create 49 nodes // also store it in m_boardPiecePlaces matrix float correctedBoardWidth = m_boardRect.size.width-BORDER_MARGIN_IN_PIXELS*2; float correctedBoardHeight = m_boardRect.size.height-BORDER_MARGIN_IN_PIXELS*2; float pieceWidth = correctedBoardWidth/(float)NUMBER_OF_COLUMNS_IN_BOARD; float pieceHeight = correctedBoardHeight/(float)NUMBER_OF_ROWS_IN_BOARD; // m_boardPiecePlaces=[[NSMutableArray alloc] init]; m_boardPiecePlaces = new CCMutableArray<CCObject *>(NUMBER_OF_ROWS_IN_BOARD); for (unsigned int column=0; column<NUMBER_OF_COLUMNS_IN_BOARD; column++) { //NSMutableArray* rows=[[NSMutableArray alloc] init]; CCMutableArray<CCObject *> *rows = new CCMutableArray<CCObject*>(NUMBER_OF_ROWS_IN_BOARD); for (unsigned int row=0; row<NUMBER_OF_ROWS_IN_BOARD; row++) { float x=pieceWidth*0.5+pieceWidth*column-correctedBoardWidth*0.5; float y=pieceHeight*0.5+pieceHeight*row-correctedBoardHeight*0.5; CCSize size; size.width = pieceWidth; size.height = pieceHeight; //BoardPiecePlace* boardPiecePlace=[[BoardPiecePlace alloc] initWithBoard:self Column:column Row:row PieceSize:size]; //boardPiecePlace.position=ccp(x,y); //[m_boardPiecePlacesPivotNode addChild:boardPiecePlace]; //[rows addObject:boardPiecePlace]; //[boardPiecePlace release]; } //[m_boardPiecePlaces addObject:rows]; rows->release(); } // init vars m_playingScene = playingScene; } Board* pLayer = new Board(); if (pLayer) { pLayer->autorelease(); return pLayer; } CC_SAFE_DELETE(pLayer); return NULL; }
[ [ [ 1, 193 ] ] ]
5f7e24650fb0430d86a91cc424ab5b638022ef3f
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/type_traits/test/tricky_function_type_test.cpp
c776b71fce9080d31370b56d0feb049b6f511a70
[ "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
5,486
cpp
// (C) Copyright John Maddock 2002. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include "check_integral_constant.hpp" #ifdef TEST_STD # include <type_traits> #else # include <boost/type_traits/is_function.hpp> # include <boost/type_traits/is_float.hpp> # include <boost/type_traits/is_enum.hpp> # include <boost/type_traits/is_class.hpp> # include <boost/type_traits/is_scalar.hpp> # include <boost/type_traits/is_pod.hpp> # include <boost/type_traits/has_trivial_constructor.hpp> # include <boost/type_traits/has_trivial_copy.hpp> # include <boost/type_traits/has_trivial_assign.hpp> # include <boost/type_traits/has_trivial_destructor.hpp> # include <boost/type_traits/is_compound.hpp> # include <boost/type_traits/is_base_of.hpp> # include <boost/type_traits/is_convertible.hpp> #endif TT_TEST_BEGIN(tricky_function_type_test) BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<const int&>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<int (&)(int)>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_class<foo0_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_enum<foo0_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_scalar<foo0_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_class<foo0_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_compound<foo0_t>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pod<foo0_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_constructor<foo0_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_copy<foo0_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_assign<foo0_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<foo0_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_base_of<foo0_t, foo0_t>::value), true); // TR1 required behaviour (new to 1.34) BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<foo0_t, int>::value), false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_class<foo1_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_enum<foo1_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_scalar<foo1_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_compound<foo1_t>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pod<foo1_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_constructor<foo1_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_copy<foo1_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_assign<foo1_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<foo1_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_class<foo2_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_enum<foo2_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_scalar<foo2_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_compound<foo2_t>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pod<foo2_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_constructor<foo2_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_copy<foo2_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_assign<foo2_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<foo2_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_class<foo3_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_enum<foo3_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_scalar<foo3_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_compound<foo3_t>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pod<foo3_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_constructor<foo3_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_copy<foo3_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_assign<foo3_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<foo3_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_class<foo4_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_enum<foo4_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_scalar<foo4_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_compound<foo4_t>::value, true); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pod<foo4_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_constructor<foo4_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_copy<foo4_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_assign<foo4_t>::value, false); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::has_trivial_destructor<foo4_t>::value, false); typedef void foo5_t(int, bool, int*, int[], int, int, int, int, int ...); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<foo5_t>::value, true); typedef void (test_abc1::*vproc1)(...); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_member_function_pointer<vproc1>::value, true); typedef void (test_abc1::*vproc2)(int, char, long, ...); BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_member_function_pointer<vproc2>::value, true); typedef void (test_abc1::*vproc3)(int, char, long, long, ...)const; BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_member_function_pointer<vproc3>::value, true); TT_TEST_END
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 104 ] ] ]
6ee333a685268a2be60a665c50999421adf9d478
5399d919f33bca564bd309c448f1151e7fb6aa27
/server/thread/ThreadWindows.hpp
aca81803fda19e6f002f2c1df84ba179d7661204
[]
no_license
hotgloupi/zhttpd
bcbc37283ebf0fb401417fa1799f7f7bb286f0d5
0437ac2e34dde89abab26665df9cbee1777f1d44
refs/heads/master
2021-01-25T05:57:49.958146
2011-01-03T14:22:05
2011-01-03T14:22:05
963,056
4
0
null
null
null
null
UTF-8
C++
false
false
720
hpp
#ifdef _WIN32 # ifndef __THREADWINDOWS_HPP__ # define __THREADWINDOWS_HPP__ # include <Windows.h> # include <stdexcept> # include "thread/ITask.hpp" # include "utils/NonCopyable.hpp" # include "utils/String.hpp" namespace zhttpd { namespace implementation { class Thread : private NonCopyable { private: HANDLE _thread; bool _running; ITask* _callback_instance; static DWORD _run(Thread* thread); public: Thread(ITask* instance); ~Thread(); void join(); void quit(); }; } } # endif // !__THREADWINDOWS_HPP__ #endif // _WIN32
[ [ [ 1, 35 ] ] ]
c1364d79bbaeedc1f5861e2a6ac92d8e8627ac79
550e17ad61efc7bea2066db5844663c8b5835e4f
/Examples/Tutorial/Physics/03CharacterTerrain.cpp
61abd71fa3c093679fb2e7641eb7e26044bde742
[]
no_license
danguilliams/OpenSGToolbox
9287424c66c9c4b38856cf749a311f15d8aac4f0
102a9fb02ad1ceeaf5784e6611c2862c4ba84d61
refs/heads/master
2021-01-17T23:02:36.528911
2010-11-01T16:56:31
2010-11-01T16:56:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,559
cpp
// OpenSG Tutorial Example: Hello World // // Minimalistic OpenSG program // // This is the shortest useful OpenSG program // (if you remove all the comments ;) // // It shows how to use OpenSG together with GLUT to create a little // interactive rootNode viewer. // // General OpenSG configuration, needed everywhere #include "OSGConfig.h" // Methods to create simple geometry: boxes, spheres, tori etc. #include "OSGSimpleGeometry.h" // A little helper to simplify rootNode management and interaction #include "OSGSimpleSceneManager.h" #include "OSGSimpleMaterial.h" #include "OSGComponentTransform.h" #include "OSGTransform.h" #include "OSGTypeFactory.h" #include "OSGFieldContainerFactory.h" #include "OSGNameAttachment.h" #include "OSGGeoFunctions.h" #include "OSGSceneFileHandler.h" #include "OSGPointLight.h" #include "OSGGradientBackground.h" #include "OSGGeoProperties.h" #include "OSGTypedGeoIntegralProperty.h" #include "OSGTypedGeoVectorProperty.h" // Input #include "OSGKeyListener.h" #include "OSGWindowUtils.h" //Physics #include "OSGPhysics.h" // Activate the OpenSG namespace // This is not strictly necessary, you can also prefix all OpenSG symbols // with OSG::, but that would be a bit tedious for this example OSG_USING_NAMESPACE // forward declaration so we can have the interesting stuff upfront void display(void); void reshape(Vec2f Size); PhysicsBodyRefPtr buildBox(Vec3f Dimensions, Pnt3f Position); PhysicsBodyRefPtr buildCharacter(Vec3f Dimensions, Pnt3f Position); GeometryRefPtr buildTerrain(Vec2f Dimensions, UInt32 XSubdivisions, UInt32 YSubdivisions); PhysicsLMotorJointRefPtr buildMover(PhysicsBodyRefPtr character); // The SimpleSceneManager to manage simple applications SimpleSceneManager *mgr; WindowEventProducerRefPtr TutorialWindow; PhysicsHandlerRefPtr physHandler; PhysicsWorldRefPtr physicsWorld; PhysicsHashSpaceRefPtr physicsSpace; PhysicsBodyRefPtr CharacterPhysicsBody; PhysicsLMotorJointRefPtr CharacterMover; Vec3f ForceOnCharacter; bool _IsUpKeyDown(false); bool _IsDownKeyDown(false); bool _IsLeftKeyDown(false); bool _IsRightKeyDown(false); bool _IsAKeyDown(false); bool _IsDKeyDown(false); bool _ShouldJump(false); //just for hierarchy NodeRefPtr spaceGroupNode; NodeRefPtr rootNode; // Create a class to allow for the use of the Ctrl+q class TutorialKeyListener : public KeyListener { public: virtual void keyPressed(const KeyEventUnrecPtr e) { if(e->getKey() == KeyEvent::KEY_Q && e->getModifiers() & KeyEvent::KEY_MODIFIER_COMMAND) { TutorialWindow->closeWindow(); } switch(e->getKey()) { case KeyEvent::KEY_B: buildBox(Vec3f(10.0,10.0,10.0), Pnt3f((Real32)(rand()%100)-50.0,(Real32)(rand()%100)-50.0,55.0)); break; case KeyEvent::KEY_UP: _IsUpKeyDown = true; break; case KeyEvent::KEY_DOWN: _IsDownKeyDown = true; break; case KeyEvent::KEY_LEFT: _IsLeftKeyDown = true; break; case KeyEvent::KEY_RIGHT: _IsRightKeyDown = true; break; case KeyEvent::KEY_A: _IsAKeyDown = true; break; case KeyEvent::KEY_D: _IsDKeyDown = true; break; case KeyEvent::KEY_SPACE: _ShouldJump = true; break; } } virtual void keyReleased(const KeyEventUnrecPtr e) { switch(e->getKey()) { case KeyEvent::KEY_UP: _IsUpKeyDown = false; break; case KeyEvent::KEY_DOWN: _IsDownKeyDown = false; break; case KeyEvent::KEY_LEFT: _IsLeftKeyDown = false; break; case KeyEvent::KEY_RIGHT: _IsRightKeyDown = false; break; case KeyEvent::KEY_A: _IsAKeyDown = false; break; case KeyEvent::KEY_D: _IsDKeyDown = false; break; } } virtual void keyTyped(const KeyEventUnrecPtr e) { } }; class TutorialMouseListener : public MouseListener { public: virtual void mouseClicked(const MouseEventUnrecPtr e) { } virtual void mouseEntered(const MouseEventUnrecPtr e) { } virtual void mouseExited(const MouseEventUnrecPtr e) { } virtual void mousePressed(const MouseEventUnrecPtr e) { mgr->mouseButtonPress(e->getButton(), e->getLocation().x(), e->getLocation().y()); } virtual void mouseReleased(const MouseEventUnrecPtr e) { mgr->mouseButtonRelease(e->getButton(), e->getLocation().x(), e->getLocation().y()); } }; class TutorialMouseMotionListener : public MouseMotionListener { public: virtual void mouseMoved(const MouseEventUnrecPtr e) { mgr->mouseMove(e->getLocation().x(), e->getLocation().y()); } virtual void mouseDragged(const MouseEventUnrecPtr e) { mgr->mouseMove(e->getLocation().x(), e->getLocation().y()); } }; class TutorialUpdateListener : public UpdateListener { public: virtual void update(const UpdateEventUnrecPtr e) { ForceOnCharacter.setValues(0.0,0.0,0.0); Real32 PushForce(55000.0); Real32 Speed(10.0); if(_IsUpKeyDown) { ForceOnCharacter += Vec3f(0.0, PushForce, 0.0); } if(_IsDownKeyDown) { ForceOnCharacter += Vec3f(0.0, -PushForce, 0.0); } if(_IsLeftKeyDown) { ForceOnCharacter += Vec3f(-PushForce, 0.0, 0.0); } if(_IsRightKeyDown) { ForceOnCharacter += Vec3f(PushForce, 0.0, 0.0); } if(_ShouldJump) { ForceOnCharacter += Vec3f(0.0, 0.0, 50000.0); _ShouldJump = false; } if(ForceOnCharacter != Vec3f(0.0,0.0,0.0)) { CharacterPhysicsBody->setEnable(true); } if(ForceOnCharacter.x() !=0.0) { CharacterMover->setFMax(osgAbs(ForceOnCharacter.x())); CharacterMover->setVel(osgSgn(ForceOnCharacter.x())*Speed); } else { CharacterMover->setFMax(0.0); CharacterMover->setVel(0.0); } if(ForceOnCharacter.y() !=0.0) { CharacterMover->setFMax2(osgAbs(ForceOnCharacter.y())); CharacterMover->setVel2(osgSgn(ForceOnCharacter.y())*Speed); } else { CharacterMover->setFMax2(0.0); CharacterMover->setVel2(0.0); } if(ForceOnCharacter.z() !=0.0) { CharacterMover->setFMax3(osgAbs(ForceOnCharacter.z())); CharacterMover->setVel3(osgSgn(ForceOnCharacter.z())*Speed); } else { CharacterMover->setFMax3(0.0); CharacterMover->setVel3(0.0); } Real32 RotationRate(1.57); if(_IsAKeyDown) { Quaternion newRotation(CharacterPhysicsBody->getQuaternion()); newRotation.mult(Quaternion(Vec3f(0.0,0.0,1.0),RotationRate*e->getElapsedTime())); CharacterPhysicsBody->setQuaternion( newRotation ); } if(_IsDKeyDown) { Quaternion newRotation(CharacterPhysicsBody->getQuaternion()); newRotation.mult(Quaternion(Vec3f(0.0,0.0,1.0),-RotationRate*e->getElapsedTime())); CharacterPhysicsBody->setQuaternion( newRotation ); } } }; PhysicsLMotorJointRefPtr buildMover(PhysicsBodyRefPtr character) { //Create LMotor Joint PhysicsLMotorJointRefPtr TutorialLMotorJoint = PhysicsLMotorJoint::create(character->getWorld()); TutorialLMotorJoint->setFirstBody(character); TutorialLMotorJoint->setSecondBody(NULL); TutorialLMotorJoint->setNumAxes(3); TutorialLMotorJoint->setAxis1Properties(Vec3f(1.0,0.0,0.0),1); TutorialLMotorJoint->setAxis2Properties(Vec3f(0.0,1.0,0.0),1); TutorialLMotorJoint->setAxis3Properties(Vec3f(0.0,0.0,1.0),1); return TutorialLMotorJoint; } // Initialize GLUT & OpenSG and set up the rootNode int main(int argc, char **argv) { // OSG init osgInit(argc,argv); // Set up Window TutorialWindow = createNativeWindow(); TutorialWindow->initWindow(); TutorialWindow->setDisplayCallback(display); TutorialWindow->setReshapeCallback(reshape); TutorialKeyListener TheKeyListener; TutorialWindow->addKeyListener(&TheKeyListener); TutorialMouseListener TheTutorialMouseListener; TutorialMouseMotionListener TheTutorialMouseMotionListener; TutorialWindow->addMouseListener(&TheTutorialMouseListener); TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener); TutorialUpdateListener TheTutorialUpdateListener; TutorialWindow->addUpdateListener(&TheTutorialUpdateListener); // Create the SimpleSceneManager helper mgr = new SimpleSceneManager; // Tell the Manager what to manage mgr->setWindow(TutorialWindow); //Make Main Scene Node NodeRefPtr scene = makeCoredNode<Group>(); setName(scene, "scene"); rootNode = Node::create(); setName(rootNode, "rootNode"); ComponentTransformRefPtr Trans; Trans = ComponentTransform::create(); { rootNode->setCore(Trans); // add the torus as a child rootNode->addChild(scene); } //Light Beacon Matrix LightTransformMat; LightTransformMat.setTranslate(Vec3f(50.0,0.0,100.0)); TransformRefPtr LightTransform = Transform::create(); LightTransform->setMatrix(LightTransformMat); NodeRefPtr TutorialLightBeacon = Node::create(); TutorialLightBeacon->setCore(LightTransform); //Light Node PointLightRefPtr TutorialLight = PointLight::create(); TutorialLight->setBeacon(TutorialLightBeacon); NodeRefPtr TutorialLightNode = Node::create(); TutorialLightNode->setCore(TutorialLight); scene->addChild(TutorialLightNode); scene->addChild(TutorialLightBeacon); //Setup Physics Scene physicsWorld = PhysicsWorld::create(); physicsWorld->setWorldContactSurfaceLayer(0.005); physicsWorld->setAutoDisableFlag(1); physicsWorld->setAutoDisableTime(0.75); physicsWorld->setWorldContactMaxCorrectingVel(100.0); physicsWorld->setGravity(Vec3f(0.0, 0.0, -9.81)); physicsSpace = PhysicsHashSpace::create(); //Setup the default collision parameters CollisionContactParametersRefPtr DefaultCollisionParams = CollisionContactParameters::createEmpty(); DefaultCollisionParams->setMode(dContactApprox1); DefaultCollisionParams->setMu(1.0); DefaultCollisionParams->setMu2(0.0); DefaultCollisionParams->setBounce(0.0); DefaultCollisionParams->setBounceSpeedThreshold(0.0); DefaultCollisionParams->setSoftCFM(0.1); DefaultCollisionParams->setSoftERP(0.2); DefaultCollisionParams->setMotion1(0.0); DefaultCollisionParams->setMotion2(0.0); DefaultCollisionParams->setMotionN(0.0); DefaultCollisionParams->setSlip1(0.0); DefaultCollisionParams->setSlip2(0.0); physicsSpace->setDefaultCollisionParameters(DefaultCollisionParams); physHandler = PhysicsHandler::create(); physHandler->setWorld(physicsWorld); physHandler->pushToSpaces(physicsSpace); physHandler->setUpdateNode(rootNode); physHandler->attachUpdateProducer(TutorialWindow->editEventProducer()); rootNode->addAttachment(physHandler); rootNode->addAttachment(physicsWorld); rootNode->addAttachment(physicsSpace); /************************************************************************/ /* create spaces, geoms and bodys */ /************************************************************************/ //create a group for our space GroupRefPtr spaceGroup; spaceGroupNode = makeCoredNode<Group>(&spaceGroup); //create the ground terrain GeometryRefPtr TerrainGeo = buildTerrain(Vec2f(400.0,400.0),25,25); //and its Material SimpleMaterialRefPtr TerrainMat = SimpleMaterial::create(); TerrainMat->setAmbient(Color3f(0.3,0.5,0.3)); TerrainMat->setDiffuse(Color3f(0.5,0.9,0.5)); TerrainGeo->setMaterial(TerrainMat); NodeRefPtr TerrainNode = Node::create(); TerrainNode->setCore(TerrainGeo); //create ODE data PhysicsGeomRefPtr TerrainODEGeom = PhysicsTriMeshGeom::create(); //add geom to space for collision TerrainODEGeom->setSpace(physicsSpace); //set the geometryNode to fill the ode-triMesh dynamic_pointer_cast<PhysicsTriMeshGeom>(TerrainODEGeom)->setGeometryNode(TerrainNode); //add attachments //add Attachments to nodes... spaceGroupNode->addAttachment(physicsSpace); spaceGroupNode->addChild(TerrainNode); TerrainNode->addAttachment(TerrainODEGeom); TutorialLightNode->addChild(spaceGroupNode); //Create Character CharacterPhysicsBody = buildCharacter(Vec3f(5.0,5.0,10.0), Pnt3f((Real32)(rand()%100)-50.0,(Real32)(rand()%100)-50.0,25.0)); CharacterMover = buildMover(CharacterPhysicsBody); // tell the manager what to manage mgr->setRoot (rootNode); // show the whole rootNode mgr->showAll(); Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f); Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5); TutorialWindow->openWindow(WinPos, WinSize, "03CharacterTerrain"); //Enter main Loop TutorialWindow->mainLoop(); osgExit(); return 0; } // Redraw the window void display(void) { mgr->redraw(); } // React to size changes void reshape(Vec2f Size) { mgr->resize(Size.x(), Size.y()); } GeometryRefPtr buildTerrain(Vec2f Dimensions, UInt32 XSubdivisions, UInt32 YSubdivisions) { GeoUInt8PropertyRefPtr type = GeoUInt8Property::create(); type->addValue(GL_TRIANGLES); GeoPnt3fPropertyRefPtr pnts = GeoPnt3fProperty ::create(); GeoVec3fPropertyRefPtr norms = GeoVec3fProperty ::create(); Real32 ZScale(8.0); for(UInt32 i(0) ; i<XSubdivisions ; ++i) { for(UInt32 j(0) ; j<YSubdivisions ; ++j) { Real32 Theta(5*3.14159*(static_cast<Real32>(i)/static_cast<Real32>(XSubdivisions))), ThetaNext(5*3.14159*(static_cast<Real32>(i+1)/static_cast<Real32>(XSubdivisions))); // the points of the Tris pnts->addValue(Pnt3f(-Dimensions.x()/2.0+i*(Dimensions.x()/static_cast<Real32>(XSubdivisions)), Dimensions.y()/2.0-j*(Dimensions.y()/static_cast<Real32>(YSubdivisions)), ZScale*osgCos(Theta))); norms->addValue(Vec3f( 0.0,0.0,1.0)); pnts->addValue(Pnt3f(-Dimensions.x()/2.0+i*(Dimensions.x()/static_cast<Real32>(XSubdivisions)), Dimensions.y()/2.0-(j+1)*(Dimensions.y()/static_cast<Real32>(YSubdivisions)), ZScale*osgCos(Theta))); norms->addValue(Vec3f( 0.0,0.0,1.0)); pnts->addValue(Pnt3f(-Dimensions.x()/2.0+(i+1)*(Dimensions.x()/static_cast<Real32>(XSubdivisions)), Dimensions.y()/2.0-j*(Dimensions.y()/static_cast<Real32>(YSubdivisions)), ZScale*osgCos(ThetaNext))); norms->addValue(Vec3f( 0.0,0.0,1.0)); pnts->addValue(Pnt3f(-Dimensions.x()/2.0+i*(Dimensions.x()/static_cast<Real32>(XSubdivisions)), Dimensions.y()/2.0-(j+1)*(Dimensions.y()/static_cast<Real32>(YSubdivisions)), ZScale*osgCos(Theta))); norms->addValue(Vec3f( 0.0,0.0,1.0)); pnts->addValue(Pnt3f(-Dimensions.x()/2.0+(i+1)*(Dimensions.x()/static_cast<Real32>(XSubdivisions)), Dimensions.y()/2.0-(j+1)*(Dimensions.y()/static_cast<Real32>(YSubdivisions)), ZScale*osgCos(ThetaNext))); norms->addValue(Vec3f( 0.0,0.0,1.0)); pnts->addValue(Pnt3f(-Dimensions.x()/2.0+(i+1)*(Dimensions.x()/static_cast<Real32>(XSubdivisions)), Dimensions.y()/2.0-j*(Dimensions.y()/static_cast<Real32>(YSubdivisions)), ZScale*osgCos(ThetaNext))); norms->addValue(Vec3f( 0.0,0.0,1.0)); } } GeoUInt32PropertyUnrecPtr lens = GeoUInt32Property::create(); lens->addValue(pnts->size()); GeometryRefPtr Terrain = Geometry::create(); Terrain->setTypes (type); Terrain->setLengths (lens); Terrain->setPositions(pnts); Terrain->setNormals(norms); calcVertexNormals(Terrain); return Terrain; } ////////////////////////////////////////////////////////////////////////// //! build a box ////////////////////////////////////////////////////////////////////////// PhysicsBodyRefPtr buildBox(Vec3f Dimensions, Pnt3f Position) { Matrix m; //create OpenSG mesh GeometryRefPtr box; NodeRefPtr characterNode = makeBox(Dimensions.x(), Dimensions.y(), Dimensions.z(), 1, 1, 1); box = dynamic_cast<Geometry*>(characterNode->getCore()); SimpleMaterialRefPtr box_mat = SimpleMaterial::create(); box_mat->setAmbient(Color3f(0.0,0.0,0.0)); box_mat->setDiffuse(Color3f(0.0,1.0 ,1.0)); box->setMaterial(box_mat); TransformRefPtr boxTrans; NodeRefPtr boxTransNode = makeCoredNode<Transform>(&boxTrans); m.setIdentity(); m.setTranslate(Position); boxTrans->setMatrix(m); //create ODE data PhysicsBodyRefPtr boxBody = PhysicsBody::create(physicsWorld); boxBody->setPosition(Vec3f(Position)); //boxBody->setLinearDamping(0.001); //boxBody->setAngularDamping(0.001); boxBody->setBoxMass(1.0,Dimensions.x(), Dimensions.y(), Dimensions.z()); PhysicsBoxGeomRefPtr boxGeom = PhysicsBoxGeom::create(); boxGeom->setBody(boxBody); boxGeom->setSpace(physicsSpace); boxGeom->setLengths(Dimensions); //add attachments characterNode->addAttachment(boxGeom); boxTransNode->addAttachment(boxBody); boxTransNode->addChild(characterNode); //add to SceneGraph spaceGroupNode->addChild(boxTransNode); commitChanges(); return boxBody; } ////////////////////////////////////////////////////////////////////////// //! build a character ////////////////////////////////////////////////////////////////////////// PhysicsBodyRefPtr buildCharacter(Vec3f Dimensions, Pnt3f Position) { Real32 Radius(osgMax(Dimensions.x(), Dimensions.y())/2.0f); Real32 Length(Dimensions.z() - 2.0f*Radius); Matrix m; //create OpenSG mesh GeometryRefPtr box; //NodeRefPtr characterNode = makeBox(Dimensions.x(), Dimensions.y(), Dimensions.z(), 1, 1, 1); NodeRefPtr characterNode = SceneFileHandler::the()->read("Data/Jack.osb"); if(characterNode == NULL) { characterNode = makeBox(Dimensions.x(), Dimensions.y(), Dimensions.z(), 1, 1, 1); } box = dynamic_cast<Geometry*>(characterNode->getCore()); TransformRefPtr boxTrans; NodeRefPtr boxTransNode = makeCoredNode<Transform>(&boxTrans); m.setIdentity(); m.setTranslate(Position); boxTrans->setMatrix(m); //create ODE data PhysicsBodyRefPtr boxBody = PhysicsBody::create(physicsWorld); boxBody->setPosition(Vec3f(Position)); //boxBody->setLinearDamping(0.001); //boxBody->setAngularDamping(0.001); boxBody->setMaxAngularSpeed(0.0); boxBody->setCapsuleMass(1.0,3,Radius, Length); PhysicsCapsuleGeomRefPtr CapsuleGeom = PhysicsCapsuleGeom::create(); CapsuleGeom->setBody(boxBody); CapsuleGeom->setSpace(physicsSpace); CapsuleGeom->setRadius(Radius); CapsuleGeom->setLength(Length); //add attachments characterNode->addAttachment(CapsuleGeom); boxTransNode->addAttachment(boxBody); boxTransNode->addChild(characterNode); //add to SceneGraph spaceGroupNode->addChild(boxTransNode); commitChanges(); return boxBody; }
[ [ [ 1, 88 ], [ 90, 601 ] ], [ [ 89, 89 ] ] ]
f3ae9d16ffb7ff465b60cbca4cf57fa1c87d9f87
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/src/microtcl/tclCompExpr.cc
6c7d33978ecfe41a01efc56769e7c68a8be43940
[]
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
33,049
cc
/* * tclCompExpr.c -- * * This file contains the code to compile Tcl expressions. * * Copyright (c) 1997 Sun Microsystems, Inc. * Copyright (c) 1998-2000 by Scriptics Corporation. * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. * * RCS: @(#) $Id: tclCompExpr.cc,v 1.2 2003/03/23 17:12:30 brucem Exp $ */ #include "microtcl/tclInt.h" #include "microtcl/tclCompile.h" /* * The stuff below is a bit of a hack so that this file can be used in * environments that include no UNIX, i.e. no errno: just arrange to use * the errno from tclExecute.c here. */ #ifndef TCL_GENERIC_ONLY #include "microtcl/tclPort.h" #else #define NO_ERRNO_H #endif #ifdef NO_ERRNO_H extern int errno; /* Use errno from tclExecute.c. */ #define ERANGE 34 #endif /* * Boolean variable that controls whether expression compilation tracing * is enabled. */ #ifdef TCL_COMPILE_DEBUG static int traceExprComp = 0; #endif /* TCL_COMPILE_DEBUG */ /* * The ExprInfo structure describes the state of compiling an expression. * A pointer to an ExprInfo record is passed among the routines in * this module. */ typedef struct ExprInfo { Tcl_Interp *interp; /* Used for error reporting. */ Tcl_Parse *parsePtr; /* Structure filled with information about * the parsed expression. */ char *expr; /* The expression that was originally passed * to TclCompileExpr. */ char *lastChar; /* Points just after last byte of expr. */ int hasOperators; /* Set 1 if the expr has operators; 0 if * expr is only a primary. If 1 after * compiling an expr, a tryCvtToNumeric * instruction is emitted to convert the * primary to a number if possible. */ int exprIsJustVarRef; /* Set 1 if the expr consists of just a * variable reference as in the expression * of "if $b then...". Otherwise 0. If 1 the * expr is compiled out-of-line in order to * implement expr's 2 level substitution * semantics properly. */ int exprIsComparison; /* Set 1 if the top-level operator in the * expr is a comparison. Otherwise 0. If 1, * because the operands might be strings, * the expr is compiled out-of-line in order * to implement expr's 2 level substitution * semantics properly. */ } ExprInfo; /* * Definitions of numeric codes representing each expression operator. * The order of these must match the entries in the operatorTable below. * Also the codes for the relational operators (OP_LESS, OP_GREATER, * OP_LE, OP_GE, OP_EQ, and OP_NE) must be consecutive and in that order. * Note that OP_PLUS and OP_MINUS represent both unary and binary operators. */ #define OP_MULT 0 #define OP_DIVIDE 1 #define OP_MOD 2 #define OP_PLUS 3 #define OP_MINUS 4 #define OP_LSHIFT 5 #define OP_RSHIFT 6 #define OP_LESS 7 #define OP_GREATER 8 #define OP_LE 9 #define OP_GE 10 #define OP_EQ 11 #define OP_NEQ 12 #define OP_BITAND 13 #define OP_BITXOR 14 #define OP_BITOR 15 #define OP_LAND 16 #define OP_LOR 17 #define OP_QUESTY 18 #define OP_LNOT 19 #define OP_BITNOT 20 #define OP_STREQ 21 #define OP_STRNEQ 22 /* * Table describing the expression operators. Entries in this table must * correspond to the definitions of numeric codes for operators just above. */ static int opTableInitialized = 0; /* 0 means not yet initialized. */ TCL_DECLARE_MUTEX(opMutex) typedef struct OperatorDesc { char *name; /* Name of the operator. */ int numOperands; /* Number of operands. 0 if the operator * requires special handling. */ int instruction; /* Instruction opcode for the operator. * Ignored if numOperands is 0. */ } OperatorDesc; OperatorDesc operatorTable[] = { {"*", 2, INST_MULT}, {"/", 2, INST_DIV}, {"%", 2, INST_MOD}, {"+", 0}, {"-", 0}, {"<<", 2, INST_LSHIFT}, {">>", 2, INST_RSHIFT}, {"<", 2, INST_LT}, {">", 2, INST_GT}, {"<=", 2, INST_LE}, {">=", 2, INST_GE}, {"==", 2, INST_EQ}, {"!=", 2, INST_NEQ}, {"&", 2, INST_BITAND}, {"^", 2, INST_BITXOR}, {"|", 2, INST_BITOR}, {"&&", 0}, {"||", 0}, {"?", 0}, {"!", 1, INST_LNOT}, {"~", 1, INST_BITNOT}, {"eq", 2, INST_STR_EQ}, {"ne", 2, INST_STR_NEQ}, {NULL} }; /* * Hashtable used to map the names of expression operators to the index * of their OperatorDesc description. */ static Tcl_HashTable opHashTable; /* * Declarations for local procedures to this file: */ static int CompileCondExpr _ANSI_ARGS_(( Tcl_Token *exprTokenPtr, ExprInfo *infoPtr, CompileEnv *envPtr, Tcl_Token **endPtrPtr)); static int CompileLandOrLorExpr _ANSI_ARGS_(( Tcl_Token *exprTokenPtr, int opIndex, ExprInfo *infoPtr, CompileEnv *envPtr, Tcl_Token **endPtrPtr)); static int CompileMathFuncCall _ANSI_ARGS_(( Tcl_Token *exprTokenPtr, char *funcName, ExprInfo *infoPtr, CompileEnv *envPtr, Tcl_Token **endPtrPtr)); static int CompileSubExpr _ANSI_ARGS_(( Tcl_Token *exprTokenPtr, ExprInfo *infoPtr, CompileEnv *envPtr)); static void LogSyntaxError _ANSI_ARGS_((ExprInfo *infoPtr)); /* * Macro used to debug the execution of the expression compiler. */ #ifdef TCL_COMPILE_DEBUG #define TRACE(exprBytes, exprLength, tokenBytes, tokenLength) \ if (traceExprComp) { \ fprintf(stderr, "CompileSubExpr: \"%.*s\", token \"%.*s\"\n", \ (exprLength), (exprBytes), (tokenLength), (tokenBytes)); \ } #else #define TRACE(exprBytes, exprLength, tokenBytes, tokenLength) #endif /* TCL_COMPILE_DEBUG */ /* *---------------------------------------------------------------------- * * TclCompileExpr -- * * This procedure compiles a string containing a Tcl expression into * Tcl bytecodes. This procedure is the top-level interface to the * the expression compilation module, and is used by such public * procedures as Tcl_ExprString, Tcl_ExprStringObj, Tcl_ExprLong, * Tcl_ExprDouble, Tcl_ExprBoolean, and Tcl_ExprBooleanObj. * * Results: * The return value is TCL_OK on a successful compilation and TCL_ERROR * on failure. If TCL_ERROR is returned, then the interpreter's result * contains an error message. * * envPtr->maxStackDepth is updated with the maximum number of stack * elements needed to execute the expression. * * envPtr->exprIsJustVarRef is set 1 if the expression consisted of * a single variable reference as in the expression of "if $b then...". * Otherwise it is set 0. This is used to implement Tcl's two level * expression substitution semantics properly. * * envPtr->exprIsComparison is set 1 if the top-level operator in the * expr is a comparison. Otherwise it is set 0. If 1, because the * operands might be strings, the expr is compiled out-of-line in order * to implement expr's 2 level substitution semantics properly. * * Side effects: * Adds instructions to envPtr to evaluate the expression at runtime. * *---------------------------------------------------------------------- */ int TclCompileExpr(interp, script, numBytes, envPtr) Tcl_Interp *interp; /* Used for error reporting. */ char *script; /* The source script to compile. */ int numBytes; /* Number of bytes in script. If < 0, the * string consists of all bytes up to the * first null character. */ CompileEnv *envPtr; /* Holds resulting instructions. */ { ExprInfo info; Tcl_Parse parse; Tcl_HashEntry *hPtr; int maxDepth, new, i, code; /* * If this is the first time we've been called, initialize the table * of expression operators. */ if (numBytes < 0) { numBytes = (script? strlen(script) : 0); } if (!opTableInitialized) { Tcl_MutexLock(&opMutex); if (!opTableInitialized) { Tcl_InitHashTable(&opHashTable, TCL_STRING_KEYS); for (i = 0; operatorTable[i].name != NULL; i++) { hPtr = Tcl_CreateHashEntry(&opHashTable, operatorTable[i].name, &new); if (new) { Tcl_SetHashValue(hPtr, (ClientData) i); } } opTableInitialized = 1; } Tcl_MutexUnlock(&opMutex); } /* * Initialize the structure containing information abvout this * expression compilation. */ info.interp = interp; info.parsePtr = &parse; info.expr = script; info.lastChar = (script + numBytes); info.hasOperators = 0; info.exprIsJustVarRef = 1; /* will be set 0 if anything else is seen */ info.exprIsComparison = 0; /* * Parse the expression then compile it. */ maxDepth = 0; code = Tcl_ParseExpr(interp, script, numBytes, &parse); if (code != TCL_OK) { goto done; } code = CompileSubExpr(parse.tokenPtr, &info, envPtr); if (code != TCL_OK) { Tcl_FreeParse(&parse); goto done; } maxDepth = envPtr->maxStackDepth; if (!info.hasOperators) { /* * Attempt to convert the primary's object to an int or double. * This is done in order to support Tcl's policy of interpreting * operands if at all possible as first integers, else * floating-point numbers. */ TclEmitOpcode(INST_TRY_CVT_TO_NUMERIC, envPtr); } Tcl_FreeParse(&parse); done: envPtr->maxStackDepth = maxDepth; envPtr->exprIsJustVarRef = info.exprIsJustVarRef; envPtr->exprIsComparison = info.exprIsComparison; return code; } /* *---------------------------------------------------------------------- * * TclFinalizeCompilation -- * * Clean up the compilation environment so it can later be * properly reinitialized. This procedure is called by * TclFinalizeCompExecEnv() in tclObj.c, which in turn is called * by Tcl_Finalize(). * * Results: * None. * * Side effects: * Cleans up the compilation environment. At the moment, just the * table of expression operators is freed. * *---------------------------------------------------------------------- */ void TclFinalizeCompilation() { Tcl_MutexLock(&opMutex); if (opTableInitialized) { Tcl_DeleteHashTable(&opHashTable); opTableInitialized = 0; } Tcl_MutexUnlock(&opMutex); } /* *---------------------------------------------------------------------- * * CompileSubExpr -- * * Given a pointer to a TCL_TOKEN_SUB_EXPR token describing a * subexpression, this procedure emits instructions to evaluate the * subexpression at runtime. * * Results: * The return value is TCL_OK on a successful compilation and TCL_ERROR * on failure. If TCL_ERROR is returned, then the interpreter's result * contains an error message. * * envPtr->maxStackDepth is updated with the maximum number of stack * elements needed to execute the subexpression. * * envPtr->exprIsJustVarRef is set 1 if the subexpression consisted of * a single variable reference as in the expression of "if $b then...". * Otherwise it is set 0. This is used to implement Tcl's two level * expression substitution semantics properly. * * envPtr->exprIsComparison is set 1 if the top-level operator in the * subexpression is a comparison. Otherwise it is set 0. If 1, because * the operands might be strings, the expr is compiled out-of-line in * order to implement expr's 2 level substitution semantics properly. * * Side effects: * Adds instructions to envPtr to evaluate the subexpression. * *---------------------------------------------------------------------- */ static int CompileSubExpr(exprTokenPtr, infoPtr, envPtr) Tcl_Token *exprTokenPtr; /* Points to TCL_TOKEN_SUB_EXPR token * to compile. */ ExprInfo *infoPtr; /* Describes the compilation state for the * expression being compiled. */ CompileEnv *envPtr; /* Holds resulting instructions. */ { Tcl_Interp *interp = infoPtr->interp; Tcl_Token *tokenPtr, *endPtr, *afterSubexprPtr; OperatorDesc *opDescPtr; Tcl_HashEntry *hPtr; char *operator; char savedChar; int maxDepth, objIndex, opIndex, length, code; char buffer[TCL_UTF_MAX]; if (exprTokenPtr->type != TCL_TOKEN_SUB_EXPR) { panic("CompileSubExpr: token type %d not TCL_TOKEN_SUB_EXPR\n", exprTokenPtr->type); } maxDepth = 0; code = TCL_OK; /* * Switch on the type of the first token after the subexpression token. * After processing it, advance tokenPtr to point just after the * subexpression's last token. */ tokenPtr = exprTokenPtr+1; TRACE(exprTokenPtr->start, exprTokenPtr->size, tokenPtr->start, tokenPtr->size); switch (tokenPtr->type) { case TCL_TOKEN_WORD: code = TclCompileTokens(interp, tokenPtr+1, tokenPtr->numComponents, envPtr); if (code != TCL_OK) { goto done; } maxDepth = envPtr->maxStackDepth; tokenPtr += (tokenPtr->numComponents + 1); infoPtr->exprIsJustVarRef = 0; break; case TCL_TOKEN_TEXT: if (tokenPtr->size > 0) { objIndex = TclRegisterLiteral(envPtr, tokenPtr->start, tokenPtr->size, /*onHeap*/ 0); } else { objIndex = TclRegisterLiteral(envPtr, "", 0, /*onHeap*/ 0); } TclEmitPush(objIndex, envPtr); maxDepth = 1; tokenPtr += 1; infoPtr->exprIsJustVarRef = 0; break; case TCL_TOKEN_BS: length = Tcl_UtfBackslash(tokenPtr->start, (int *) NULL, buffer); if (length > 0) { objIndex = TclRegisterLiteral(envPtr, buffer, length, /*onHeap*/ 0); } else { objIndex = TclRegisterLiteral(envPtr, "", 0, /*onHeap*/ 0); } TclEmitPush(objIndex, envPtr); maxDepth = 1; tokenPtr += 1; infoPtr->exprIsJustVarRef = 0; break; case TCL_TOKEN_COMMAND: code = TclCompileScript(interp, tokenPtr->start+1, tokenPtr->size-2, /*nested*/ 1, envPtr); if (code != TCL_OK) { goto done; } maxDepth = envPtr->maxStackDepth; tokenPtr += 1; infoPtr->exprIsJustVarRef = 0; break; case TCL_TOKEN_VARIABLE: code = TclCompileTokens(interp, tokenPtr, 1, envPtr); if (code != TCL_OK) { goto done; } maxDepth = envPtr->maxStackDepth; tokenPtr += (tokenPtr->numComponents + 1); break; case TCL_TOKEN_SUB_EXPR: infoPtr->exprIsComparison = 0; code = CompileSubExpr(tokenPtr, infoPtr, envPtr); if (code != TCL_OK) { goto done; } maxDepth = envPtr->maxStackDepth; tokenPtr += (tokenPtr->numComponents + 1); break; case TCL_TOKEN_OPERATOR: /* * Look up the operator. Temporarily overwrite the character * just after the end of the operator with a 0 byte. If the * operator isn't found, treat it as a math function. */ /* * TODO: Note that the string is modified in place. This is unsafe * and will break if any of the routines called while the string is * modified have side effects that depend on the original string * being unmodified (e.g. adding an entry to the literal table). */ operator = tokenPtr->start; savedChar = operator[tokenPtr->size]; operator[tokenPtr->size] = 0; hPtr = Tcl_FindHashEntry(&opHashTable, operator); if (hPtr == NULL) { code = CompileMathFuncCall(exprTokenPtr, operator, infoPtr, envPtr, &endPtr); operator[tokenPtr->size] = (char) savedChar; if (code != TCL_OK) { goto done; } maxDepth = envPtr->maxStackDepth; tokenPtr = endPtr; infoPtr->exprIsJustVarRef = 0; infoPtr->exprIsComparison = 0; break; } operator[tokenPtr->size] = (char) savedChar; opIndex = (int) Tcl_GetHashValue(hPtr); opDescPtr = &(operatorTable[opIndex]); /* * If the operator is "normal", compile it using information * from the operator table. */ if (opDescPtr->numOperands > 0) { tokenPtr++; code = CompileSubExpr(tokenPtr, infoPtr, envPtr); if (code != TCL_OK) { goto done; } maxDepth = envPtr->maxStackDepth; tokenPtr += (tokenPtr->numComponents + 1); if (opDescPtr->numOperands == 2) { code = CompileSubExpr(tokenPtr, infoPtr, envPtr); if (code != TCL_OK) { goto done; } maxDepth = TclMax((envPtr->maxStackDepth + 1), maxDepth); tokenPtr += (tokenPtr->numComponents + 1); } TclEmitOpcode(opDescPtr->instruction, envPtr); infoPtr->hasOperators = 1; infoPtr->exprIsJustVarRef = 0; infoPtr->exprIsComparison = (((opIndex >= OP_LESS) && (opIndex <= OP_NEQ)) || ((opIndex >= OP_STREQ) && (opIndex <= OP_STRNEQ))); break; } /* * The operator requires special treatment, and is either * "+" or "-", or one of "&&", "||" or "?". */ switch (opIndex) { case OP_PLUS: case OP_MINUS: tokenPtr++; code = CompileSubExpr(tokenPtr, infoPtr, envPtr); if (code != TCL_OK) { goto done; } maxDepth = envPtr->maxStackDepth; tokenPtr += (tokenPtr->numComponents + 1); /* * Check whether the "+" or "-" is unary. */ afterSubexprPtr = exprTokenPtr + exprTokenPtr->numComponents+1; if (tokenPtr == afterSubexprPtr) { TclEmitOpcode(((opIndex==OP_PLUS)? INST_UPLUS : INST_UMINUS), envPtr); break; } /* * The "+" or "-" is binary. */ code = CompileSubExpr(tokenPtr, infoPtr, envPtr); if (code != TCL_OK) { goto done; } maxDepth = TclMax((envPtr->maxStackDepth + 1), maxDepth); tokenPtr += (tokenPtr->numComponents + 1); TclEmitOpcode(((opIndex==OP_PLUS)? INST_ADD : INST_SUB), envPtr); break; case OP_LAND: case OP_LOR: code = CompileLandOrLorExpr(exprTokenPtr, opIndex, infoPtr, envPtr, &endPtr); if (code != TCL_OK) { goto done; } maxDepth = envPtr->maxStackDepth; tokenPtr = endPtr; break; case OP_QUESTY: code = CompileCondExpr(exprTokenPtr, infoPtr, envPtr, &endPtr); if (code != TCL_OK) { goto done; } maxDepth = envPtr->maxStackDepth; tokenPtr = endPtr; break; default: panic("CompileSubExpr: unexpected operator %d requiring special treatment\n", opIndex); } /* end switch on operator requiring special treatment */ infoPtr->hasOperators = 1; infoPtr->exprIsJustVarRef = 0; infoPtr->exprIsComparison = 0; break; default: panic("CompileSubExpr: unexpected token type %d\n", tokenPtr->type); } /* * Verify that the subexpression token had the required number of * subtokens: that we've advanced tokenPtr just beyond the * subexpression's last token. For example, a "*" subexpression must * contain the tokens for exactly two operands. */ if (tokenPtr != (exprTokenPtr + exprTokenPtr->numComponents+1)) { LogSyntaxError(infoPtr); code = TCL_ERROR; } done: envPtr->maxStackDepth = maxDepth; return code; } /* *---------------------------------------------------------------------- * * CompileLandOrLorExpr -- * * This procedure compiles a Tcl logical and ("&&") or logical or * ("||") subexpression. * * Results: * The return value is TCL_OK on a successful compilation and TCL_ERROR * on failure. If TCL_OK is returned, a pointer to the token just after * the last one in the subexpression is stored at the address in * endPtrPtr. If TCL_ERROR is returned, then the interpreter's result * contains an error message. * * envPtr->maxStackDepth is updated with the maximum number of stack * elements needed to execute the expression. * * Side effects: * Adds instructions to envPtr to evaluate the expression at runtime. * *---------------------------------------------------------------------- */ static int CompileLandOrLorExpr(exprTokenPtr, opIndex, infoPtr, envPtr, endPtrPtr) Tcl_Token *exprTokenPtr; /* Points to TCL_TOKEN_SUB_EXPR token * containing the "&&" or "||" operator. */ int opIndex; /* A code describing the expression * operator: either OP_LAND or OP_LOR. */ ExprInfo *infoPtr; /* Describes the compilation state for the * expression being compiled. */ CompileEnv *envPtr; /* Holds resulting instructions. */ Tcl_Token **endPtrPtr; /* If successful, a pointer to the token * just after the last token in the * subexpression is stored here. */ { JumpFixup shortCircuitFixup; /* Used to fix up the short circuit jump * after the first subexpression. */ JumpFixup lhsTrueFixup, lhsEndFixup; /* Used to fix up jumps used to convert the * first operand to 0 or 1. */ Tcl_Token *tokenPtr; int dist, maxDepth, code; /* * Emit code for the first operand. */ maxDepth = 0; tokenPtr = exprTokenPtr+2; code = CompileSubExpr(tokenPtr, infoPtr, envPtr); if (code != TCL_OK) { goto done; } maxDepth = envPtr->maxStackDepth; tokenPtr += (tokenPtr->numComponents + 1); /* * Convert the first operand to the result that Tcl requires: * "0" or "1". Eventually we'll use a new instruction for this. */ TclEmitForwardJump(envPtr, TCL_TRUE_JUMP, &lhsTrueFixup); TclEmitPush(TclRegisterLiteral(envPtr, "0", 1, /*onHeap*/ 0), envPtr); TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &lhsEndFixup); dist = (envPtr->codeNext - envPtr->codeStart) - lhsTrueFixup.codeOffset; if (TclFixupForwardJump(envPtr, &lhsTrueFixup, dist, 127)) { badDist: panic("CompileLandOrLorExpr: bad jump distance %d\n", dist); } TclEmitPush(TclRegisterLiteral(envPtr, "1", 1, /*onHeap*/ 0), envPtr); dist = (envPtr->codeNext - envPtr->codeStart) - lhsEndFixup.codeOffset; if (TclFixupForwardJump(envPtr, &lhsEndFixup, dist, 127)) { goto badDist; } /* * Emit the "short circuit" jump around the rest of the expression. * Duplicate the "0" or "1" on top of the stack first to keep the * jump from consuming it. */ TclEmitOpcode(INST_DUP, envPtr); TclEmitForwardJump(envPtr, ((opIndex==OP_LAND)? TCL_FALSE_JUMP : TCL_TRUE_JUMP), &shortCircuitFixup); /* * Emit code for the second operand. */ code = CompileSubExpr(tokenPtr, infoPtr, envPtr); if (code != TCL_OK) { goto done; } maxDepth = TclMax((envPtr->maxStackDepth + 1), maxDepth); tokenPtr += (tokenPtr->numComponents + 1); /* * Emit a "logical and" or "logical or" instruction. This does not try * to "short- circuit" the evaluation of both operands, but instead * ensures that we either have a "1" or a "0" result. */ TclEmitOpcode(((opIndex==OP_LAND)? INST_LAND : INST_LOR), envPtr); /* * Now that we know the target of the forward jump, update it with the * correct distance. */ dist = (envPtr->codeNext - envPtr->codeStart) - shortCircuitFixup.codeOffset; TclFixupForwardJump(envPtr, &shortCircuitFixup, dist, 127); *endPtrPtr = tokenPtr; done: envPtr->maxStackDepth = maxDepth; return code; } /* *---------------------------------------------------------------------- * * CompileCondExpr -- * * This procedure compiles a Tcl conditional expression: * condExpr ::= lorExpr ['?' condExpr ':' condExpr] * * Results: * The return value is TCL_OK on a successful compilation and TCL_ERROR * on failure. If TCL_OK is returned, a pointer to the token just after * the last one in the subexpression is stored at the address in * endPtrPtr. If TCL_ERROR is returned, then the interpreter's result * contains an error message. * * envPtr->maxStackDepth is updated with the maximum number of stack * elements needed to execute the expression. * * Side effects: * Adds instructions to envPtr to evaluate the expression at runtime. * *---------------------------------------------------------------------- */ static int CompileCondExpr(exprTokenPtr, infoPtr, envPtr, endPtrPtr) Tcl_Token *exprTokenPtr; /* Points to TCL_TOKEN_SUB_EXPR token * containing the "?" operator. */ ExprInfo *infoPtr; /* Describes the compilation state for the * expression being compiled. */ CompileEnv *envPtr; /* Holds resulting instructions. */ Tcl_Token **endPtrPtr; /* If successful, a pointer to the token * just after the last token in the * subexpression is stored here. */ { JumpFixup jumpAroundThenFixup, jumpAroundElseFixup; /* Used to update or replace one-byte jumps * around the then and else expressions when * their target PCs are determined. */ Tcl_Token *tokenPtr; int elseCodeOffset, dist, maxDepth, code; /* * Emit code for the test. */ maxDepth = 0; tokenPtr = exprTokenPtr+2; code = CompileSubExpr(tokenPtr, infoPtr, envPtr); if (code != TCL_OK) { goto done; } maxDepth = envPtr->maxStackDepth; tokenPtr += (tokenPtr->numComponents + 1); /* * Emit the jump to the "else" expression if the test was false. */ TclEmitForwardJump(envPtr, TCL_FALSE_JUMP, &jumpAroundThenFixup); /* * Compile the "then" expression. Note that if a subexpression is only * a primary, we need to try to convert it to numeric. We do this to * support Tcl's policy of interpreting operands if at all possible as * first integers, else floating-point numbers. */ infoPtr->hasOperators = 0; code = CompileSubExpr(tokenPtr, infoPtr, envPtr); if (code != TCL_OK) { goto done; } maxDepth = TclMax(envPtr->maxStackDepth, maxDepth); tokenPtr += (tokenPtr->numComponents + 1); if (!infoPtr->hasOperators) { TclEmitOpcode(INST_TRY_CVT_TO_NUMERIC, envPtr); } /* * Emit an unconditional jump around the "else" condExpr. */ TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &jumpAroundElseFixup); /* * Compile the "else" expression. */ elseCodeOffset = (envPtr->codeNext - envPtr->codeStart); infoPtr->hasOperators = 0; code = CompileSubExpr(tokenPtr, infoPtr, envPtr); if (code != TCL_OK) { goto done; } maxDepth = TclMax(envPtr->maxStackDepth, maxDepth); tokenPtr += (tokenPtr->numComponents + 1); if (!infoPtr->hasOperators) { TclEmitOpcode(INST_TRY_CVT_TO_NUMERIC, envPtr); } /* * Fix up the second jump around the "else" expression. */ dist = (envPtr->codeNext - envPtr->codeStart) - jumpAroundElseFixup.codeOffset; if (TclFixupForwardJump(envPtr, &jumpAroundElseFixup, dist, 127)) { /* * Update the else expression's starting code offset since it * moved down 3 bytes too. */ elseCodeOffset += 3; } /* * Fix up the first jump to the "else" expression if the test was false. */ dist = (elseCodeOffset - jumpAroundThenFixup.codeOffset); TclFixupForwardJump(envPtr, &jumpAroundThenFixup, dist, 127); *endPtrPtr = tokenPtr; done: envPtr->maxStackDepth = maxDepth; return code; } /* *---------------------------------------------------------------------- * * CompileMathFuncCall -- * * This procedure compiles a call on a math function in an expression: * mathFuncCall ::= funcName '(' [condExpr {',' condExpr}] ')' * * Results: * The return value is TCL_OK on a successful compilation and TCL_ERROR * on failure. If TCL_OK is returned, a pointer to the token just after * the last one in the subexpression is stored at the address in * endPtrPtr. If TCL_ERROR is returned, then the interpreter's result * contains an error message. * * envPtr->maxStackDepth is updated with the maximum number of stack * elements needed to execute the function. * * Side effects: * Adds instructions to envPtr to evaluate the math function at * runtime. * *---------------------------------------------------------------------- */ static int CompileMathFuncCall(exprTokenPtr, funcName, infoPtr, envPtr, endPtrPtr) Tcl_Token *exprTokenPtr; /* Points to TCL_TOKEN_SUB_EXPR token * containing the math function call. */ char *funcName; /* Name of the math function. */ ExprInfo *infoPtr; /* Describes the compilation state for the * expression being compiled. */ CompileEnv *envPtr; /* Holds resulting instructions. */ Tcl_Token **endPtrPtr; /* If successful, a pointer to the token * just after the last token in the * subexpression is stored here. */ { Tcl_Interp *interp = infoPtr->interp; Interp *iPtr = (Interp *) interp; MathFunc *mathFuncPtr; Tcl_HashEntry *hPtr; Tcl_Token *tokenPtr, *afterSubexprPtr; int maxDepth, code, i; /* * Look up the MathFunc record for the function. */ code = TCL_OK; maxDepth = 0; hPtr = Tcl_FindHashEntry(&iPtr->mathFuncTable, funcName); if (hPtr == NULL) { Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), "unknown math function \"", funcName, "\"", (char *) NULL); code = TCL_ERROR; goto done; } mathFuncPtr = (MathFunc *) Tcl_GetHashValue(hPtr); /* * If not a builtin function, push an object with the function's name. */ if (mathFuncPtr->builtinFuncIndex < 0) { TclEmitPush(TclRegisterLiteral(envPtr, funcName, -1, /*onHeap*/ 0), envPtr); maxDepth = 1; } /* * Compile any arguments for the function. */ tokenPtr = exprTokenPtr+2; afterSubexprPtr = exprTokenPtr + (exprTokenPtr->numComponents + 1); if (mathFuncPtr->numArgs > 0) { for (i = 0; i < mathFuncPtr->numArgs; i++) { if (tokenPtr == afterSubexprPtr) { Tcl_ResetResult(interp); Tcl_AppendToObj(Tcl_GetObjResult(interp), "too few arguments for math function", -1); code = TCL_ERROR; goto done; } infoPtr->exprIsComparison = 0; code = CompileSubExpr(tokenPtr, infoPtr, envPtr); if (code != TCL_OK) { goto done; } tokenPtr += (tokenPtr->numComponents + 1); maxDepth++; } if (tokenPtr != afterSubexprPtr) { Tcl_ResetResult(interp); Tcl_AppendToObj(Tcl_GetObjResult(interp), "too many arguments for math function", -1); code = TCL_ERROR; goto done; } } else if (tokenPtr != afterSubexprPtr) { Tcl_ResetResult(interp); Tcl_AppendToObj(Tcl_GetObjResult(interp), "too many arguments for math function", -1); code = TCL_ERROR; goto done; } /* * Compile the call on the math function. Note that the "objc" argument * count for non-builtin functions is incremented by 1 to include the * function name itself. */ if (mathFuncPtr->builtinFuncIndex >= 0) { /* a builtin function */ TclEmitInstInt1(INST_CALL_BUILTIN_FUNC1, mathFuncPtr->builtinFuncIndex, envPtr); } else { TclEmitInstInt1(INST_CALL_FUNC1, (mathFuncPtr->numArgs+1), envPtr); } *endPtrPtr = afterSubexprPtr; done: envPtr->maxStackDepth = maxDepth; return code; } /* *---------------------------------------------------------------------- * * LogSyntaxError -- * * This procedure is invoked after an error occurs when compiling an * expression. It sets the interpreter result to an error message * describing the error. * * Results: * None. * * Side effects: * Sets the interpreter result to an error message describing the * expression that was being compiled when the error occurred. * *---------------------------------------------------------------------- */ static void LogSyntaxError(infoPtr) ExprInfo *infoPtr; /* Describes the compilation state for the * expression being compiled. */ { int numBytes = (infoPtr->lastChar - infoPtr->expr); char buffer[100]; sprintf(buffer, "syntax error in expression \"%.*s\"", ((numBytes > 60)? 60 : numBytes), infoPtr->expr); Tcl_AppendStringsToObj(Tcl_GetObjResult(infoPtr->interp), buffer, (char *) NULL); }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 1054 ] ] ]
8a306093eb427e4d6d6d0bd530ce9feeb4c869f4
a5de878687ee2e72db865481785dafbeda373e2a
/trunck/OpenPR-0.0.2/sci_gateway/qdmatch/Match.h
d10a471fca7c1c10a5d0b6aec0ae0ebc9f5b5fa1
[ "BSD-3-Clause" ]
permissive
Augertron/OpenPR
8f43102fd5811d26301ef75e0a1f2b6ba9cbdb73
e2b1ce89f020c1b25df8ac5d93f6a0014ed4f714
refs/heads/master
2020-05-15T09:31:08.385577
2011-03-21T02:51:40
2011-03-21T02:51:40
182,178,910
0
0
null
null
null
null
UTF-8
C++
false
false
3,985
h
////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2009 OpenPR // 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 OpenPR 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 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 HOLDER AND 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. //////////////////////////////////////////////////////////////////////////// // Match.h -- Declaration of the class Match. #ifndef MATCH_H #define MATCH_H #include "Keypoint.h" class Match; ostream & operator <<(ostream &os, const Match &match); istream & operator >>(istream &is, Match &match); class Point { public: Point(void); Point(double x, double y); Point(const Keypoint &key); // ~Point(void); double GetX(void) const; double GetY(void) const; friend ostream & operator <<(ostream &os, const Match &match); friend istream & operator >>(istream &is, Match &match); private: double m_x; double m_y; }; class Match { public: Match(); Match(const Point &target, const Point &found, double dist); Match(const Match &other); //~Match(void); Match & operator =(const Match &other); friend ostream & operator <<(ostream &os, const Match &match); friend istream & operator >>(istream &is, Match &match); Point GetTarget(void) const; Point GetFound(void) const; double GetDist(void) const; int GetIsKey(void) const; void SetIsKey(int isKey); inline bool operator< (const Match& match) const { // Compare the ZNCC correlation score. return (m_dist > match.m_dist); } inline bool operator> (const Match& match) const { // Compare the ZNCC correlation score. return (m_dist <= match.m_dist); } //int CompareTo(const Match &match); private: Point m_target; // matched point from the first image. Point m_found; // matched point from the second image. // Before correlation, it is distance between the matched points. // After correlation, it is correlation score between the match. double m_dist; // Mark if the match includes an interest point, 1 yes, 0 no. int m_isKey; }; //bool operator <(Match &match1, const Match &match2); // Sometimes m_dist stores the similarity measure value like // correlation coefficient, which is the larger, the better. //bool less_match(Match &match1, const Match &match2); //ostream & operator <<(ostream &os, const Match &match); //istream & operator >>(istream &is, Match &match); bool WriteMatchFile(const string& fileName, const vector<Match> &matches); bool ReadMatchFile(vector<Match> &matches, const char *fileName); bool WriteMatchFile(const string& fileName, vector<Match>* pMatch01, const vector<Match> &match12); #endif
[ "openpr@9318c073-892e-421e-b8e5-d5f98a2b248e" ]
[ [ [ 1, 124 ] ] ]
43505f55bbb9f95d3e5e6ff73bfc4027d640650c
63c7e5c07ef73c3d53088ec124a940d383fbfd81
/Source/GPhysics/GPhysicsManager.cpp
dba51f9983e3392ac95be91c5f1232fde983e45e
[]
no_license
dgoemans/openrage
f66e01f0a3e81f760e62d9058f5d6b21d71c2000
fa7d2fc52f3df17d60373736c8061d2560e0ebac
refs/heads/master
2020-02-26T14:33:32.803806
2008-03-14T15:01:25
2008-03-14T15:01:25
32,354,718
0
0
null
null
null
null
UTF-8
C++
false
false
2,292
cpp
#include "GPhysicsManager.h" //================================================================== GPhysicsManager::GPhysicsManager() : mTotalTime( 0.0 ), mBodies( ) { } //================================================================== GPhysicsManager::~GPhysicsManager() { std::list<GRigidBody*>::iterator it = mBodies.begin(); while( mBodies.end() != it++ ) { delete *it; } } //================================================================== void GPhysicsManager::Solve( double deltaTime ) { std::list<GRigidBody*>::iterator it = mBodies.begin(); for( it = mBodies.begin(); it != mBodies.end(); ++it ) { GRigidBody* current = *it; Integration::State bodyState; bodyState.position = current->GetPosition(); bodyState.velocity = current->GetVelocity(); Integration::State first = current->EvaluateFirstDerivative( bodyState, mTotalTime ); Integration::State secondHalf1 = current->EvaluateSecondDerivative( bodyState, mTotalTime, deltaTime*0.5f, first ); Integration::State secondHalf2 = current->EvaluateSecondDerivative( bodyState, mTotalTime, deltaTime*0.5f, secondHalf1 ); Integration::State thirdHalf2 = current->EvaluateSecondDerivative( bodyState, mTotalTime, deltaTime, secondHalf2 ); const CwMtx::CWTVector<double> dxdt = 1.0/6.0 * (first.position + (secondHalf1.position + secondHalf2.position)*2.0 + thirdHalf2.position); const CwMtx::CWTVector<double> dvdt = 1.0/6.0 * (first.velocity + (secondHalf1.velocity + secondHalf2.velocity)*2.0 + thirdHalf2.velocity); bodyState.position = bodyState.position + dxdt*deltaTime; bodyState.velocity = bodyState.velocity + dvdt*deltaTime; } mTotalTime += deltaTime; } //================================================================== GRigidBody* GPhysicsManager::AddBody( CwMtx::CWTVector<double> position, CwMtx::CWTQuaternion<double> rotation, double mass, double inertia ) { mBodies.push_back( new GRigidBody( position, rotation, mass, inertia ) ); return mBodies.back(); } //==================================================================
[ "dgoemans@36ee989d-3a48-0410-af8a-351069dbcf3a" ]
[ [ [ 1, 64 ] ] ]
3900aca41fcad51091b2a1e0aed40432b1813cc4
119ba245bea18df8d27b84ee06e152b35c707da1
/unreal/branches/svn/qrgui/parsers/hascol/hascolParser.h
641db78c5538d8b85f29e00abbde6fe5322aeae7
[]
no_license
nfrey/qreal
05cd4f9b9d3193531eb68ff238d8a447babcb3d2
71641e6c5f8dc87eef9ec3a01cabfb9dd7b0e164
refs/heads/master
2020-04-06T06:43:41.910531
2011-05-30T19:30:09
2011-05-30T19:30:09
1,634,768
0
0
null
null
null
null
UTF-8
C++
false
false
1,489
h
#pragma once #include <QtCore/QString> #include <QtXml/QDomElement> #include "../../kernel/ids.h" #include "../../mainwindow/errorReporter.h" namespace qrRepo { class RepoApi; } namespace qReal { class EditorManager; namespace parsers { class HascolParser { public: explicit HascolParser(qrRepo::RepoApi &api, EditorManager const &editorManager); gui::ErrorReporter parse(QStringList const &files); private: Id mImportedPortMappingDiagramId; Id mImportedStructureDiagramId; qrRepo::RepoApi &mApi; EditorManager const &mEditorManager; gui::ErrorReporter mErrorReporter; Id initDiagram(QString const &diagramName, QString const &diagramType); Id addElement(Id const &parent, Id const &elementType, QString const &name); void preprocessFile(QString const &fileName); void parseFile(QString const &fileName); void parseProcess(QDomElement const &element); void parsePorts(QDomNodeList const &ports, QString const &direction , Id const &parentOnAPortMap, Id const &parentOnAStructure); void initClassifierFields(Id const &classifier); void doLayout(Id const &diagram, unsigned cellWidth, unsigned cellHeight); void doPortMappingLayout(); void doStructureLayout(); void doPlugsLayout(Id const &parent); void doPortsLayout(Id const &parent); void doLayoutForPortsType(Id const &parent, unsigned margin, QString const &direction, unsigned count); }; } }
[ [ [ 1, 52 ] ] ]
c68570c6ee2d79ac66f175243b6f2e2cde376847
96e96a73920734376fd5c90eb8979509a2da25c0
/C3DE/FX.cpp
5eed1ea382f9c5cde8b76b905055eb08bc0318c6
[]
no_license
lianlab/c3de
9be416cfbf44f106e2393f60a32c1bcd22aa852d
a2a6625549552806562901a9fdc083c2cacc19de
refs/heads/master
2020-04-29T18:07:16.973449
2009-11-15T10:49:36
2009-11-15T10:49:36
32,124,547
0
0
null
null
null
null
UTF-8
C++
false
false
2,416
cpp
#include "FX.h" #include "DebugMemory.h" FX::FX(ID3DXEffect * effect) { m_effect = effect; m_shaderTechnique = m_effect->GetTechniqueByName("ShaderTech"); m_shaderViewMatrix = m_effect->GetParameterByName(0, "gWVP"); m_shaderEyePosition= m_effect->GetParameterByName(0, "gEyePosW"); m_shaderWorldMatrix = m_effect->GetParameterByName(0, "gWorld"); m_shaderWorldInverseTransposeMatrix = m_effect->GetParameterByName(0, "gWorldInvTrans"); m_shaderAmbientLightMaterial = m_effect->GetParameterByName(0, "gAmbientLight"); m_shaderDiffuseLightMaterial = m_effect->GetParameterByName(0, "gDiffuseLight"); m_shaderSpecularLightMaterial = m_effect->GetParameterByName(0, "gSpecularLight"); m_shaderLightPosition = m_effect->GetParameterByName(0, "gLightVecW"); m_shaderTransformMatrix = m_effect->GetParameterByName(0, "gTransformMatrix"); D3DXMATRIX T; D3DXMatrixIdentity(&T); SetTransformMatrix(T); } FX::~FX() { } void FX::SetTransformMatrix(D3DXMATRIX matrix) { if(m_shaderTransformMatrix) { HR(m_effect->SetValue(m_shaderTransformMatrix, &matrix, sizeof(D3DXMATRIX))); } } void FX::SetLightHandlers( D3DXCOLOR ambientLightColor, D3DXCOLOR diffuseLightColor, D3DXCOLOR specularLightColor, D3DXVECTOR3 lightVector) { if(m_shaderLightPosition) { HR(m_effect->SetValue(m_shaderLightPosition, &lightVector, sizeof(D3DXVECTOR3))); } if(m_shaderAmbientLightMaterial) { HR(m_effect->SetValue(m_shaderAmbientLightMaterial, &ambientLightColor, sizeof(D3DXCOLOR))); } if(m_shaderDiffuseLightMaterial) { HR(m_effect->SetValue(m_shaderDiffuseLightMaterial, &diffuseLightColor, sizeof(D3DXCOLOR))); } if(m_shaderSpecularLightMaterial) { HR(m_effect->SetValue(m_shaderSpecularLightMaterial, &specularLightColor, sizeof(D3DXCOLOR))); } } void FX::SetWorldHandlers(D3DXVECTOR3 cameraPosition, D3DXMATRIX worldViewProjection) { D3DXMATRIX W; D3DXMatrixIdentity(&W); D3DXMATRIX WIT; D3DXMatrixInverse(&WIT, 0, &W); D3DXMatrixTranspose(&WIT, &WIT); HR(m_effect->SetMatrix(m_shaderWorldMatrix, &W)); HR(m_effect->SetMatrix(m_shaderViewMatrix, &worldViewProjection)); HR(m_effect->SetMatrix(m_shaderWorldInverseTransposeMatrix, &WIT)); HR(m_effect->SetValue(m_shaderEyePosition, cameraPosition, sizeof(D3DXVECTOR3))); }
[ "caiocsabino@7e2be596-0d54-0410-9f9d-cf4183935158" ]
[ [ [ 1, 88 ] ] ]
0a8fac1ccf5f1a984698ab17befe2ef9881b75e8
9d1cb48ec6f6c1f0e342f0f8f819cbda74ceba6e
/src/OrgGroupDlg.cpp
234bd598ccc1a01cdbd53c3b2b15416697a422a6
[]
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
18,582
cpp
// OrgGroupDlg.cpp : implementation file // #include "stdafx.h" #include "VeryIE.h" #include "MainFrm.h" #include "OrgGroupDlg.h" #include "GroupUrlDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define INTERNET_MAX_PATH_LENGTH 2048 //#pragma optimize( "s", on ) ///////////////////////////////////////////////////////////////////////////// // COrgGroupDlg dialog COrgGroupDlg::COrgGroupDlg(CWnd* pParent /*=NULL*/) : CDialog(COrgGroupDlg::IDD, pParent) { //{{AFX_DATA_INIT(COrgGroupDlg) //}}AFX_DATA_INIT m_pDragImage = NULL; } void COrgGroupDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(COrgGroupDlg) DDX_Control(pDX, IDC_CLOSE_ALL_BEFORE_NEW_GROUP, m_CloseAllBeforeNewGroup); DDX_Control(pDX, IDC_SHOW_GROUP_MEMBER, m_GroupShowMember); DDX_Control(pDX, IDC_INSERT, m_btnInsert); DDX_Control(pDX, IDC_URL_LIST, m_UrlList); DDX_Control(pDX, IDC_GROUP_LIST, m_GroupList); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(COrgGroupDlg, CDialog) //{{AFX_MSG_MAP(COrgGroupDlg) ON_NOTIFY(LVN_ITEMCHANGED, IDC_GROUP_LIST, OnSelChanging) ON_BN_CLICKED(IDC_NEW_GROUP, OnNewGroup) ON_BN_CLICKED(IDC_DEL_GROUP, OnDelGroup) ON_BN_CLICKED(IDC_DELETE, OnDelete) ON_NOTIFY(LVN_ENDLABELEDIT, IDC_GROUP_LIST, OnEndlabeleditGroupList) ON_BN_CLICKED(IDC_INSERT, OnInsert) ON_BN_CLICKED(IDC_UPDATE, OnUpdate) ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN1, OnDeltaposSpin1) ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN2, OnDeltaposSpin2) ON_NOTIFY(NM_CLICK, IDC_GROUP_LIST, OnClickGroupList) ON_NOTIFY(LVN_BEGINDRAG, IDC_URL_LIST, OnBegindragUrlList) ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_NOTIFY(NM_DBLCLK, IDC_URL_LIST, OnDblclkUrlList) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // COrgGroupDlg message handlers BOOL COrgGroupDlg::OnInitDialog() { #ifdef _WRITE_LNG_FILE_ _WriteDlgString(this,"DialogGroup"); this->OnCancel(); return TRUE; #endif LOADDLG("DialogGroup"); CDialog::OnInitDialog(); m_bInit = TRUE; // TODO: Add extra initialization here m_GroupList.SetExtendedStyle(m_GroupList.GetExtendedStyle()|LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT); m_UrlList.SetExtendedStyle(m_UrlList.GetExtendedStyle() | LVS_EX_FULLROWSELECT|LVS_EX_CHECKBOXES); //setup list ctrl CRect rect; m_GroupList.InsertColumn(0,""); m_GroupList.GetWindowRect(rect); m_GroupList.SetColumnWidth(0, rect.Width()-25); CString str; LOADSTR(str ,IDS_NAME); m_UrlList.InsertColumn(0,str); m_UrlList.GetWindowRect(rect); m_UrlList.SetColumnWidth(0, 100); LOADSTR(str ,IDS_URL); m_UrlList.InsertColumn(1,str); m_UrlList.SetColumnWidth(1, rect.Width()-125); //load group list m_strStartGroup = pmf->m_strStartGroup; int i=0; CString strMenu; for (i=0; i<=pmf->m_astrGroup.GetUpperBound(); i++) { strMenu = pmf->m_astrGroup.GetAt(i); strMenu = strMenu.Left(strMenu.GetLength()-4); m_GroupList.InsertItem(i, strMenu); if(strMenu == m_strStartGroup) { m_GroupList.SetCheck(i); } } m_GroupList.SetItemState(0, LVIS_SELECTED, LVIS_SELECTED); m_nLastSelItemID = -1; FillUrlList(0); if(i==0) m_btnInsert.EnableWindow(FALSE); m_bInit = FALSE; m_GroupShowMember.SetCheck( pmf->m_bGroupMenuShowMember ); m_CloseAllBeforeNewGroup.SetCheck( pmf->m_bCloseAllBeforeNewGroup); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void COrgGroupDlg::FillUrlList(int index) { try{ if(m_nLastSelItemID == index) return; if(m_nLastSelItemID>=0) SaveUrlList(m_nLastSelItemID); m_nLastSelItemID = index; //remove all first m_UrlList.DeleteAllItems(); m_UrlList.SetItemCount(0); if(index<0) return; CString filename; filename = m_GroupList.GetItemText(index, 0); filename = theApp.m_strGroupPath + filename+".cgp"; char state[10]="state",name[9]="name",url[8]="url",download[13]="download"; // x+5 int i=0,nState; char tmp[INTERNET_MAX_PATH_LENGTH]; BOOL r = TRUE; DWORD dwProperty; while(r) { itoa(i, state+5, 10); itoa(i, name+4, 10); itoa(i, url+3, 10); itoa(i, download+8, 10); nState = ::GetPrivateProfileInt("Group", state, 1, filename); r = ::GetPrivateProfileString("Group", name, NULL, tmp, INTERNET_MAX_PATH_LENGTH, filename); if (r) { m_UrlList.InsertItem(i, tmp); m_UrlList.SetCheck(i, nState); r = ::GetPrivateProfileString("Group", url, NULL, tmp, INTERNET_MAX_PATH_LENGTH, filename); if (r) m_UrlList.SetItemText(i,1,tmp); dwProperty = ::GetPrivateProfileInt("Group", download, DEFAULT_PROPERTY, filename); m_UrlList.SetItemData(i,dwProperty); } i++; } }catch(...){} } void COrgGroupDlg::SaveUrlList(int index) { try{ if(index<0) return; CString filename; filename = m_GroupList.GetItemText(index, 0); if(filename.IsEmpty()) return; char state[10]="state",name[9]="name",url[8]="url",download[13]="download"; // x+5 char num[15]; filename = theApp.m_strGroupPath + filename+".cgp"; int n = m_UrlList.GetItemCount(); WritePrivateProfileSection("Group", NULL, filename); for( int i=0; i<n; i++) { itoa(i, state+5, 10); itoa(i, name+4, 10); itoa(i, url+3, 10); itoa(i, download+8, 10); if (m_UrlList.GetCheck(i)==FALSE) { itoa( 0, num, 10); ::WritePrivateProfileString("Group", state, num, filename); } ::WritePrivateProfileString("Group", name, m_UrlList.GetItemText(i,0), filename); ::WritePrivateProfileString("Group", url, m_UrlList.GetItemText(i,1), filename); if (m_UrlList.GetItemData(i) != DEFAULT_PROPERTY) { ultoa( m_UrlList.GetItemData(i), num, 10); ::WritePrivateProfileString("Group", download, num, filename); } } }catch(...){} } void COrgGroupDlg::OnSelChanging(NMHDR* pNMHDR, LRESULT* pResult) { if(m_bInit) return; NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR; // TODO: Add your control notification handler code here int i = m_GroupList.GetSelectedCount(); if(i>0) { POSITION pos = m_GroupList.GetFirstSelectedItemPosition(); int item = m_GroupList.GetNextSelectedItem(pos); FillUrlList(item); m_btnInsert.EnableWindow(1); } else { FillUrlList(-1); m_btnInsert.EnableWindow(0); } *pResult = 0; } void COrgGroupDlg::OnNewGroup() { // TODO: Add your control notification handler code here CString def, str; LOADSTR(def ,IDS_NEW_GROUP); str = def; char si[5]; int i=0; LVFINDINFO info; info.flags = LVFI_STRING; info.psz = str; while (m_GroupList.FindItem(&info) != -1) { i++; itoa(i, si, 10); str = def + " ("; str += si; str += ")"; info.psz = str; } i = m_GroupList.GetItemCount(); m_GroupList.InsertItem(i, str); m_GroupList.SetFocus(); m_GroupList.SetItemState(i, LVIS_SELECTED, LVIS_SELECTED); CString filename; filename = theApp.m_strGroupPath + str+".cgp"; HANDLE hfile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); CloseHandle(hfile); m_GroupList.EnsureVisible(i,FALSE); m_GroupList.EditLabel(i); } void COrgGroupDlg::OnDelGroup() { // TODO: Add your control notification handler code here int i = m_GroupList.GetSelectedCount(); if(i>0) { POSITION pos = m_GroupList.GetFirstSelectedItemPosition(); int item = m_GroupList.GetNextSelectedItem(pos); if(MSGBOX(IDS_CONFIRM_DEL, MB_YESNO|MB_ICONQUESTION) == IDYES) { BOOL rem = FALSE; CString filename; filename = m_GroupList.GetItemText(item, 0); if(filename == m_strStartGroup) rem = TRUE; filename = theApp.m_strGroupPath + filename+".cgp"; if(DeleteFile(filename)) { m_nLastSelItemID = -1; m_GroupList.DeleteItem(item); m_UrlList.DeleteAllItems(); if(rem) m_strStartGroup = ""; } // LIST_FOCUS_POS(m_GroupList, item); } } } void COrgGroupDlg::OnEndlabeleditGroupList(NMHDR* pNMHDR, LRESULT* pResult) { LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pNMHDR; // TODO: Add your control notification handler code here CString str; m_GroupList.GetEditControl()->GetWindowText(str); str.TrimLeft(); str.TrimRight(); //rename file CString filename; BOOL ren = FALSE; filename = m_GroupList.GetItemText(pDispInfo->item.iItem, 0); if(filename == m_strStartGroup) ren = TRUE; filename = theApp.m_strGroupPath + filename+".cgp"; if(MoveFile(filename, theApp.m_strGroupPath + str + ".cgp")) { m_GroupList.SetItemText(pDispInfo->item.iItem,0,str); if(ren) m_strStartGroup = str; } *pResult = 0; } void COrgGroupDlg::OnOK() { // TODO: Add extra validation here int i = m_GroupList.GetSelectedCount(); if(i>0) { POSITION pos = m_GroupList.GetFirstSelectedItemPosition(); int item = m_GroupList.GetNextSelectedItem(pos); SaveUrlList(item); } pmf->m_strStartGroup = m_strStartGroup; pmf->m_bGroupMenuShowMember = m_GroupShowMember.GetCheck(); pmf->m_bCloseAllBeforeNewGroup = m_CloseAllBeforeNewGroup.GetCheck(); //get order CString strItem; CString strOrder; for (i=0;i<m_GroupList.GetItemCount();i++) { strItem = m_GroupList.GetItemText(i,0); strOrder += strItem; strOrder += ".cgp\r\n"; } //write order CFile f; if(f.Open(theApp.m_strGroupPath+"order.txt", CFile::modeCreate|CFile::modeWrite|CFile::shareDenyNone)) { f.Write((void*)(LPCSTR)strOrder, strOrder.GetLength()); f.Close(); } // CDialog::OnOK(); } void COrgGroupDlg::OnDelete() { // TODO: Add your control notification handler code here int i = m_UrlList.GetSelectedCount(); if(i>0) { POSITION pos = m_UrlList.GetFirstSelectedItemPosition(); int item = m_UrlList.GetNextSelectedItem(pos); m_UrlList.DeleteItem(item); // LIST_FOCUS_POS(m_UrlList,item); } } void COrgGroupDlg::OnInsert() { // TODO: Add your control notification handler code here if(m_nLastSelItemID<0) return; CGroupUrlDlg dlg; dlg.m_bNotEmpty = FALSE; if(dlg.DoModal() == IDOK) { CString str = dlg.m_strName; str.TrimLeft(); str.TrimRight(); if(str.IsEmpty()) GetUnqBlankName(str); dlg.m_strUrl.TrimLeft(); int item; LIST_GET_INSERT_POS(m_UrlList,&item); m_UrlList.InsertItem(item, str); m_UrlList.SetItemText(item, 1, dlg.m_strUrl); m_UrlList.SetCheck(item,dlg.m_bState); m_UrlList.SetItemData(item, dlg.m_dwProperty); LIST_FOCUS_POS (m_UrlList, item); } } void COrgGroupDlg::OnUpdate() { // TODO: Add your control notification handler code here int item; int i = m_UrlList.GetSelectedCount(); if(i>0) { POSITION pos = m_UrlList.GetFirstSelectedItemPosition(); item = m_UrlList.GetNextSelectedItem(pos); } else return; CGroupUrlDlg dlg; dlg.m_strName = m_UrlList.GetItemText(item, 0); dlg.m_strUrl = m_UrlList.GetItemText(item,1); dlg.m_bState = m_UrlList.GetCheck(item); dlg.m_dwProperty = m_UrlList.GetItemData(item); if(dlg.DoModal() == IDOK) { CString str = dlg.m_strName; str.TrimLeft(); str.TrimRight(); if(str.IsEmpty()) GetUnqBlankName(str); m_UrlList.SetItemText(item, 0, str); dlg.m_strUrl.TrimLeft(); m_UrlList.SetItemText(item, 1, dlg.m_strUrl); m_UrlList.SetCheck(item, dlg.m_bState); m_UrlList.SetItemData(item,dlg.m_dwProperty); } } void COrgGroupDlg::OnDeltaposSpin1(NMHDR* pNMHDR, LRESULT* pResult) { NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR; // TODO: Add your control notification handler code here POSITION pos = m_GroupList.GetFirstSelectedItemPosition(); int nItem = -1, newItem; if(pos!=NULL) { nItem = m_GroupList.GetNextSelectedItem(pos); if(pNMUpDown->iDelta<0) newItem = nItem -1; else newItem = nItem + 1; int n = m_GroupList.GetItemCount(); if(newItem>=0 && newItem<n) { CString str = m_GroupList.GetItemText(nItem,0); BOOL bState = m_GroupList.GetCheck(nItem); m_GroupList.DeleteItem(nItem); m_GroupList.InsertItem(newItem, str); m_GroupList.SetItemState(newItem, LVIS_SELECTED, LVIS_SELECTED); m_GroupList.SetCheck(newItem, bState); m_GroupList.EnsureVisible(newItem, FALSE); } } *pResult = 0; } void COrgGroupDlg::OnDeltaposSpin2(NMHDR* pNMHDR, LRESULT* pResult) { NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR; // TODO: Add your control notification handler code here POSITION pos = m_UrlList.GetFirstSelectedItemPosition(); int nItem = -1, newItem; if(pos!=NULL) { nItem = m_UrlList.GetNextSelectedItem(pos); if(pNMUpDown->iDelta<0) newItem = nItem -1; else newItem = nItem + 1; int n = m_UrlList.GetItemCount(); if(newItem>=0 && newItem<n) { CString str = m_UrlList.GetItemText(nItem,0); CString str2 = m_UrlList.GetItemText(nItem, 1); BOOL bState = m_UrlList.GetCheck(nItem); DWORD dwProperty= m_UrlList.GetItemData(nItem); m_UrlList.DeleteItem(nItem); m_UrlList.InsertItem(newItem, str); m_UrlList.SetItemText(newItem, 1, str2); m_UrlList.SetItemState(newItem, LVIS_SELECTED, LVIS_SELECTED); m_UrlList.SetCheck(newItem, bState); m_UrlList.SetItemData(newItem, dwProperty); m_UrlList.EnsureVisible(newItem, FALSE); } } *pResult = 0; } void COrgGroupDlg::GetUnqBlankName(CString &newblnk) { CString def = "blank"; newblnk = def; char si[5]; int i=0; LVFINDINFO info; info.flags = LVFI_STRING; do{ i++; itoa(i, si, 10); newblnk = def; newblnk += si; info.psz = newblnk; }while(m_UrlList.FindItem(&info) != -1); } void COrgGroupDlg::OnClickGroupList(NMHDR* pNMHDR, LRESULT* pResult) { // TODO: Add your control notification handler code here CPoint pt; UINT flag; GetCursorPos(&pt); m_GroupList.ScreenToClient(&pt); int iItem = m_GroupList.HitTest(pt, &flag); if(flag != LVHT_ONITEMSTATEICON || iItem<0) return; BOOL bcheck = m_GroupList.GetCheck(iItem); LVFINDINFO info; info.flags = LVFI_STRING; info.psz = m_strStartGroup; int item = m_GroupList.FindItem(&info); if(!bcheck) { m_GroupList.SetCheck(item, 0); //m_GroupList.SetCheck(iItem); m_strStartGroup = m_GroupList.GetItemText(iItem, 0); } else if(iItem == item) { m_strStartGroup = ""; } *pResult = 0; } void COrgGroupDlg::OnBegindragUrlList(NMHDR* pNMHDR, LRESULT* pResult) { NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR; // TODO: Add your control notification handler code here m_nDragIndex = pNMListView->iItem; POINT pt; pt.x = 8; pt.y = 8; // create a drag image if(m_pDragImage) delete m_pDragImage; m_pDragImage = m_UrlList.CreateDragImage (m_nDragIndex, &pt); ASSERT (m_pDragImage); // changes the cursor to the drag image (DragMove() is still required in // OnMouseMove()) VERIFY (m_pDragImage->BeginDrag (0, CPoint (8, 8))); VERIFY (m_pDragImage->DragEnter (GetDesktopWindow (), pNMListView->ptAction)); // set dragging flag m_bDragging = TRUE; m_nDropIndex = -1; m_pDropWnd = &m_GroupList; // capture all mouse messages SetCapture (); *pResult = 0; } void COrgGroupDlg::OnLButtonUp(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default if (m_bDragging) { // release mouse capture VERIFY (::ReleaseCapture ()); m_bDragging = FALSE; // end dragging VERIFY (m_pDragImage->DragLeave (GetDesktopWindow ())); m_pDragImage->EndDrag (); // turn off hilight for previous drop target m_GroupList.SetItemState (m_nDropIndex, 0, LVIS_DROPHILITED); // redraw previous item m_GroupList.RedrawItems (m_nDropIndex, m_nDropIndex); CPoint pt (point); ClientToScreen (&pt); // get the CWnd pointer of the window that is under the mouse cursor // if window is CTreeCtrl CWnd* pDropWnd = WindowFromPoint (pt); if (pDropWnd == m_pDropWnd && m_nDropIndex>=0 && m_nDropIndex!=m_nLastSelItemID) { CString name = m_UrlList.GetItemText(m_nDragIndex,0); CString url = m_UrlList.GetItemText(m_nDragIndex,1); BOOL bState = m_UrlList.GetCheck(m_nDragIndex); DWORD dwProperty= m_UrlList.GetItemData(m_nDragIndex); //add to new list CString filename; filename = m_GroupList.GetItemText(m_nDropIndex, 0); filename = theApp.m_strGroupPath + filename+".cgp"; //::WritePrivateProfileString("CaptorGroup", name, url, filename); _GroupAddItem(name,url,bState,dwProperty,filename); if(!PRESS_CTRL) OnDelete(); } } CDialog::OnLButtonUp(nFlags, point); } void COrgGroupDlg::OnMouseMove(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default if (m_bDragging) { CPoint pt (point); ClientToScreen (&pt); // move the drag image VERIFY (m_pDragImage->DragMove (pt)); // unlock window updates VERIFY (m_pDragImage->DragShowNolock (FALSE)); // get the CWnd pointer of the window that is under the mouse cursor CWnd* pDropWnd = WindowFromPoint (pt); ASSERT (pDropWnd); // convert from screen coordinates to drop target client coordinates pDropWnd->ScreenToClient (&pt); // if window is CTreeCtrl if (pDropWnd == m_pDropWnd) { UINT uFlags; CListCtrl* pList = (CListCtrl*)pDropWnd; // turn off hilight for previous drop target pList->SetItemState (m_nDropIndex, 0, LVIS_DROPHILITED); // redraw previous item pList->RedrawItems (m_nDropIndex, m_nDropIndex); // get the item that is below cursor m_nDropIndex = ((CListCtrl*)pDropWnd)->HitTest (pt, &uFlags); // highlight it if(m_nDropIndex>=0) { pList->SetItemState (m_nDropIndex, LVIS_DROPHILITED, LVIS_DROPHILITED); // redraw item pList->RedrawItems (m_nDropIndex, m_nDropIndex); pList->UpdateWindow (); } } // lock window updates VERIFY (m_pDragImage->DragShowNolock (TRUE)); } CDialog::OnMouseMove(nFlags, point); } void COrgGroupDlg::OnDblclkUrlList(NMHDR* pNMHDR, LRESULT* pResult) { // TODO: Add your control notification handler code here int item; int i = m_UrlList.GetSelectedCount(); if(i>0) { POSITION pos = m_UrlList.GetFirstSelectedItemPosition(); item = m_UrlList.GetNextSelectedItem(pos); } else return; OnUpdate();//pmf->NewChildWindow(1,2, m_UrlList.GetItemText(item,1)); *pResult = 0; } //#pragma optimize( "s", off)
[ "songbohr@af2e6244-03f2-11de-b556-9305e745af9e" ]
[ [ [ 1, 695 ] ] ]
1df010bdc4913c611825fc5f4b786049feb100a9
da9e4cd28021ecc9e17e48ac3ded33b798aae59c
/SAMPLES/DSHOWFILTERS/mpeg4ip_mp4v2/src/atom_video.cpp
1a7f00c759230f309eb523d9e4da68f771c63741
[]
no_license
hibive/sjmt6410pm090728
d45242e74b94f954cf0960a4392f07178088e560
45ceea6c3a5a28172f7cd0b439d40c494355015c
refs/heads/master
2021-01-10T10:02:35.925367
2011-01-27T04:22:44
2011-01-27T04:22:44
43,739,703
1
1
null
null
null
null
UTF-8
C++
false
false
2,423
cpp
/* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is MPEG4IP. * * The Initial Developer of the Original Code is Cisco Systems Inc. * Portions created by Cisco Systems Inc. are * Copyright (C) Cisco Systems Inc. 2004. All Rights Reserved. * * Contributor(s): * Bill May [email protected] */ #include "mp4common.h" MP4VideoAtom::MP4VideoAtom (const char *type) : MP4Atom(type) { AddReserved("reserved1", 6); /* 0 */ AddProperty( /* 1 */ new MP4Integer16Property("dataReferenceIndex")); AddReserved("reserved2", 16); /* 2 */ AddProperty( /* 3 */ new MP4Integer16Property("width")); AddProperty( /* 4 */ new MP4Integer16Property("height")); AddReserved("reserved3", 14); /* 5 */ MP4StringProperty* pProp = new MP4StringProperty("compressorName"); pProp->SetFixedLength(32); pProp->SetValue(""); AddProperty(pProp); /* 6 */ AddProperty(/* 7 */ new MP4Integer16Property("depth")); AddProperty(/* 8 */ new MP4Integer16Property("colorTableId")); ExpectChildAtom("smi ", Optional, OnlyOne); } void MP4VideoAtom::Generate() { MP4Atom::Generate(); ((MP4Integer16Property*)m_pProperties[1])->SetValue(1); // property reserved3 has non-zero fixed values static u_int8_t reserved3[14] = { 0x00, 0x48, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }; m_pProperties[5]->SetReadOnly(false); ((MP4BytesProperty*)m_pProperties[5])-> SetValue(reserved3, sizeof(reserved3)); m_pProperties[5]->SetReadOnly(true); // depth and color table id values - should be set later // as far as depth - color table is most likely 0xff ((MP4IntegerProperty *)m_pProperties[7])->SetValue(0x18); ((MP4IntegerProperty *)m_pProperties[8])->SetValue(0xffff); }
[ "jhlee74@a3c55b0e-9d05-11de-8bf8-05dd22f30006" ]
[ [ [ 1, 78 ] ] ]
7c2be6aa77b623083f9e3509cde14067ac3cf3e2
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/richedit.hpp
1878da62b88d7c5d6559de30abc5455d8b8ad59e
[]
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,396
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'RichEdit.pas' rev: 6.00 #ifndef RichEditHPP #define RichEditHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <Windows.hpp> // Pascal unit #include <Messages.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- #include <RichEdit.h> namespace Richedit { //-- type declarations ------------------------------------------------------- #pragma pack(push, 4) struct TCharFormatA { unsigned cbSize; int dwMask; int dwEffects; int yHeight; int yOffset; unsigned crTextColor; Byte bCharSet; Byte bPitchAndFamily; char szFaceName[32]; } ; #pragma pack(pop) #pragma pack(push, 4) struct TCharFormatW { unsigned cbSize; int dwMask; int dwEffects; int yHeight; int yOffset; unsigned crTextColor; Byte bCharSet; Byte bPitchAndFamily; wchar_t szFaceName[32]; } ; #pragma pack(pop) typedef TCharFormatA TCharFormat; typedef _charrange TCharRange; typedef TEXTRANGEA TTextRangeA; typedef TEXTRANGEW TTextRangeW; typedef TEXTRANGEA TEXTRANGE; typedef int __stdcall (*TEditStreamCallBack)(int dwCookie, System::PByte pbBuff, int cb, int &pcb); typedef _editstream TEditStream; typedef FINDTEXTA FINDTEXT; typedef FINDTEXTA TFindTextA; typedef FINDTEXTW TFindTextW; typedef FINDTEXTA TFindText; typedef FINDTEXTEXA FINDTEXTEX; typedef FINDTEXTEXA TFindTextExA; typedef FINDTEXTEXW TFindTextExW; typedef FINDTEXTEXA TFindTextEx; typedef _formatrange TFormatRange; typedef _paraformat TParaFormat; typedef CHARFORMAT2A CHARFORMAT2; typedef CHARFORMAT2A TCharFormat2A; typedef CHARFORMAT2W TCharFormat2W; typedef PARAFORMAT2 TParaFormat2; typedef _msgfilter *PMsgFilter; typedef _msgfilter TMsgFilter; struct TReqSize; typedef TReqSize *PReqSize; #pragma pack(push, 1) struct TReqSize { tagNMHDR nmhdr; Types::TRect rc; } ; #pragma pack(pop) typedef _selchange *PSelChange; typedef _selchange TSelChange; #pragma pack(push, 4) struct TEndDropFiles { tagNMHDR nmhdr; unsigned hDrop; int cp; BOOL fProtected; } ; #pragma pack(pop) typedef _enprotected *PENProtected; typedef _enprotected TENProtected; typedef _ensaveclipboard *PENSaveClipboard; typedef _ensaveclipboard TENSaveClipboard; typedef ENOLEOPFAILED TENOleOpFailed; typedef OBJECTPOSITIONS TObjectPositions; typedef ENLINK TENLink; typedef _encorrecttext TENCorrectText; typedef _punctuation TPunctuation; typedef _compcolor TCompColor; typedef _repastespecial TRepasteSpecial; typedef GETTEXTEX TGetTextEx; typedef GETTEXTLENGTHEX TGetTextLengthEx; //-- var, const, procedure --------------------------------------------------- #define RICHEDIT_CLASS10A "RICHEDIT" static const Shortint FT_MATCHCASE = 0x4; static const Shortint FT_WHOLEWORD = 0x2; } /* namespace Richedit */ using namespace Richedit; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // RichEdit
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 163 ] ] ]
8cc50082d03fecd6483fb52ccb7826eebfb230c4
ef99cef8dc1995c6535a131e46cd89dda30fcecd
/MainFrm.h
8e5b26d9e66d172a1592145a9d08f6d387be1249
[]
no_license
sundapeng/snlcomplier
37b738db9631355621d872e4156c971927a6d7ce
13a5318454dcb9c405b0cfc29a3371df6274ee24
refs/heads/master
2016-09-05T15:44:33.901594
2010-07-02T04:56:09
2010-07-02T04:56:09
32,118,730
1
1
null
null
null
null
UTF-8
C++
false
false
887
h
// MainFrm.h : interface of the CMainFrame class // ///////////////////////////////////////////////////////////////////////////// #pragma once #include "Predefine.h" class CMainFrame : public CFrameWnd { protected: // create from serialization only CMainFrame(); DECLARE_DYNCREATE(CMainFrame) // Attributes public: // Operations public: // Overrides virtual BOOL PreCreateWindow(CREATESTRUCT& cs); // Implementation public: virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // control bar embedded members CStatusBar m_wndStatusBar; CToolBar m_wndToolBar; // Generated message map functions protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg LRESULT OnErrorReport(WPARAM wParam,LPARAM lParam); DECLARE_MESSAGE_MAP() };
[ "[email protected]@a7bbafab-dc4b-51e6-8110-5f81b14c7997" ]
[ [ [ 1, 41 ] ] ]
129832088e63467ee499b1b00355abc649802377
16d8b25d0d1c0f957c92f8b0d967f71abff1896d
/OblivionOnlineServer/Module.h
e61bc2dc70306768bc20fce5dbdce0a042ea92a9
[]
no_license
wlasser/oonline
51973b5ffec0b60407b63b010d0e4e1622cf69b6
fd37ee6985f1de082cbc9f8625d1d9307e8801a6
refs/heads/master
2021-05-28T23:39:16.792763
2010-05-12T22:35:20
2010-05-12T22:35:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,788
h
#pragma once /* This file is part of OblivionOnline Server- An open source game server for the OblivionOnline mod Copyright (C) 2008 Julian Bangert This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "GlobalDefines.h" #include "ExternInterface.h" #ifdef WIN32 #include <Windows.h> #endif class Module { public: Module(ModuleManager *mm,GameServer * gs,std::string Filename); // Module has to contain an exported procedure called "OnLoad" ~Module(void); const GUID& GetGUID() { return plugin->modid; } const GUID& GetVersionID() { return plugin->versionid; } const int GetVersion() { return plugin->Version; } const char *Name() { return plugin->Name; } const char *Author() { return plugin->Author; } const char *Website() { return plugin->Website; } const char *AuthorEmail() { return plugin->AuthorEmail; } const char *VersionName() { return plugin->VersionName; } PluginInfo * GetPluginInfo() { return plugin; } private: void *m_data; // implementation specific - WIN32: Hmodule is a void* ... GameServer *m_gs; PluginInfo *plugin; ModuleManager *m_mm; };
[ "masterfreek64@2644d07b-d655-0410-af38-4bee65694944", "obliviononline@2644d07b-d655-0410-af38-4bee65694944" ]
[ [ [ 1, 1 ], [ 20, 20 ], [ 23, 30 ], [ 67, 68 ], [ 73, 74 ] ], [ [ 2, 19 ], [ 21, 22 ], [ 31, 66 ], [ 69, 72 ] ] ]
9caeca5aa0fe2424c3c43b328d7e0edcbcd68a39
94c1c7459eb5b2826e81ad2750019939f334afc8
/source/CTaiScreenTestDetial.h
e878202c468edb2489572122bcaa606efeb0b41d
[]
no_license
wgwang/yinhustock
1c57275b4bca093e344a430eeef59386e7439d15
382ed2c324a0a657ddef269ebfcd84634bd03c3a
refs/heads/master
2021-01-15T17:07:15.833611
2010-11-27T07:06:40
2010-11-27T07:06:40
37,531,026
1
3
null
null
null
null
UTF-8
C++
false
false
1,275
h
//{{AFX_INCLUDES() #include "msflexgrid.h" //}}AFX_INCLUDES #if !defined(AFX_SCREENSTOCKTESTDETIAL_H__0D839826_62CE_11D4_970B_0080C8D6450E__INCLUDED_) #define AFX_SCREENSTOCKTESTDETIAL_H__0D839826_62CE_11D4_970B_0080C8D6450E__INCLUDED_ #include "CTaiShanDoc.h" // Added by ClassView #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // CTaiScreenTestDetial.h : header file class CTaiScreenTestDetial : public CDialog { public: CString m_stockname; SCREEN_DETAIL detail; void SetDetail(SCREEN_RESULT *chooseresult,CString stockname); SCREEN_RESULT *m_chooseresult; CTaiScreenTestDetial(CWnd* pParent = NULL); //{{AFX_DATA(CTaiScreenTestDetial) enum { IDD = IDD_DIATJXGDETAIL }; CButtonST m_ok; CMSFlexGrid m_flexgrid; //}}AFX_DATA //{{AFX_VIRTUAL(CTaiScreenTestDetial) protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL protected: //{{AFX_MSG(CTaiScreenTestDetial) virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_SCREENSTOCKTESTDETIAL_H__0D839826_62CE_11D4_970B_0080C8D6450E__INCLUDED_)
[ [ [ 1, 52 ] ] ]
e80520350d583401ef0e6f983ceaaee7105946b6
bef7d0477a5cac485b4b3921a718394d5c2cf700
/testLotsOfGuys/src/demo/ComplexStuffEntity.h
db850ded7cd746f5bd2553a13d6057624e46234b
[ "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
1,416
h
#ifndef __COMPLEX_STUFF_ENTITY_H #define __COMPLEX_STUFF_ENTITY_H #include <dingus/renderer/RenderableSkin.h> #include <dingus/gfx/skeleton/CharacterAnimator.h> #include <dingus/gfx/skeleton/SkinUpdater.h> #include "DemoResources.h" // -------------------------------------------------------------------------- inline static double gGetAnimDuration( const CAnimationBunch& b, bool loopLast ) { const CAnimationBunch::TVector3Animation* a = b.findVector3Anim("pos"); assert( a ); return (a->getLength() - (loopLast ? 0 : 1)) / ANIM_FPS; } // -------------------------------------------------------------------------- class CComplexStuffEntity : public boost::noncopyable { public: CComplexStuffEntity( const char* name, const char* defaultAnim, float defAnimFadeInTime = 0.1f ); ~CComplexStuffEntity(); void render(); void update( time_value timenow ); const SMatrix4x4& getWorldMatrix() const { return mAnimator->getRootMatrix(); } SMatrix4x4& getWorldMatrix() { return mAnimator->getRootMatrix(); } const CCharacterAnimator& getAnimator() const { return *mAnimator; } CCharacterAnimator& getAnimator() { return *mAnimator; } CSkinUpdater& getSkinUpdater() { return *mSkinUpdater; } CRenderableSkin* getMesh() { return mMesh; } protected: CRenderableSkin* mMesh; CCharacterAnimator* mAnimator; CSkinUpdater* mSkinUpdater; }; #endif
[ [ [ 1, 47 ] ] ]
493445c66a500026ee943a39052fcf5cda699bcc
ce87282d8a4674b2c67bde4b7dbac165af73715b
/src/propgrid/editors.cpp
7c6fd030d78ff28415297c1eb541336acd0fb72d
[]
no_license
Bluehorn/wxPython
b07ffc08b99561d222940753ab5074c6a85ba962
7b04577e268c59f727d4aadea6ba8a78638e3c1b
refs/heads/master
2021-01-24T04:20:21.023240
2007-08-15T21:01:30
2016-01-23T00:46:02
8,418,914
0
1
null
null
null
null
UTF-8
C++
false
false
76,569
cpp
///////////////////////////////////////////////////////////////////////////// // Name: editors.cpp // Purpose: wxPropertyGrid editors // Author: Jaakko Salli // Modified by: // Created: Apr-14-2007 // RCS-ID: $Id: // Copyright: (c) Jaakko Salli // Licence: wxWindows license ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/defs.h" #include "wx/object.h" #include "wx/hash.h" #include "wx/string.h" #include "wx/log.h" #include "wx/event.h" #include "wx/window.h" #include "wx/panel.h" #include "wx/dc.h" #include "wx/dcclient.h" #include "wx/dcmemory.h" #include "wx/button.h" #include "wx/pen.h" #include "wx/brush.h" #include "wx/cursor.h" #include "wx/dialog.h" #include "wx/settings.h" #include "wx/msgdlg.h" #include "wx/choice.h" #include "wx/stattext.h" #include "wx/scrolwin.h" #include "wx/dirdlg.h" #include "wx/layout.h" #include "wx/sizer.h" #include "wx/textdlg.h" #include "wx/filedlg.h" #include "wx/statusbr.h" #include "wx/intl.h" #include "wx/frame.h" #endif #include "wx/timer.h" #include "wx/dcbuffer.h" #include "wx/bmpbuttn.h" // This define is necessary to prevent macro clearing #define __wxPG_SOURCE_FILE__ #include <wx/propgrid/propgrid.h> #include <wx/propgrid/propdev.h> #include <wx/propgrid/editors.h> #include <wx/propgrid/props.h> #if 1 // defined(__WXPYTHON__) #include <wx/propgrid/advprops.h> #include <wx/propgrid/extras.h> #endif #if wxPG_USE_RENDERER_NATIVE #include <wx/renderer.h> #endif // How many pixels between textctrl and button #ifdef __WXMAC__ // Backported from wx2.9 by Julian Smart (old value was 8) #define wxPG_TEXTCTRL_AND_BUTTON_SPACING 4 #else #define wxPG_TEXTCTRL_AND_BUTTON_SPACING 2 #endif #define wxPG_BUTTON_SIZEDEC 0 #if wxPG_USING_WXOWNERDRAWNCOMBOBOX #include <wx/odcombo.h> #else #include <wx/propgrid/odcombo.h> #endif #ifdef __WXMSW__ #include <wx/msw/private.h> #endif // ----------------------------------------------------------------------- #if defined(__WXMSW__) // tested #define wxPG_NAT_TEXTCTRL_BORDER_X 0 // Unremovable border of native textctrl. #define wxPG_NAT_TEXTCTRL_BORDER_Y 0 // Unremovable border of native textctrl. #define wxPG_NAT_BUTTON_BORDER_ANY 1 #define wxPG_NAT_BUTTON_BORDER_X 1 #define wxPG_NAT_BUTTON_BORDER_Y 1 #define wxPG_CHECKMARK_XADJ 1 #define wxPG_CHECKMARK_YADJ (-1) #define wxPG_CHECKMARK_WADJ 0 #define wxPG_CHECKMARK_HADJ 0 #define wxPG_CHECKMARK_DEFLATE 0 #define wxPG_TEXTCTRLYADJUST (m_spacingy+0) #elif defined(__WXGTK__) // tested #define wxPG_CHECKMARK_XADJ 0 #define wxPG_CHECKMARK_YADJ 0 #define wxPG_CHECKMARK_WADJ (-1) #define wxPG_CHECKMARK_HADJ (-1) #define wxPG_CHECKMARK_DEFLATE 3 #define wxPG_NAT_TEXTCTRL_BORDER_X 3 // Unremovable border of native textctrl. #define wxPG_NAT_TEXTCTRL_BORDER_Y 3 // Unremovable border of native textctrl. #define wxPG_NAT_BUTTON_BORDER_ANY 1 #define wxPG_NAT_BUTTON_BORDER_X 1 #define wxPG_NAT_BUTTON_BORDER_Y 1 #define wxPG_TEXTCTRLYADJUST 0 #elif defined(__WXMAC__) // *not* tested #define wxPG_CHECKMARK_XADJ 0 #define wxPG_CHECKMARK_YADJ 0 #define wxPG_CHECKMARK_WADJ 0 #define wxPG_CHECKMARK_HADJ 0 #define wxPG_CHECKMARK_DEFLATE 0 #define wxPG_NAT_TEXTCTRL_BORDER_X 0 // Unremovable border of native textctrl. #define wxPG_NAT_TEXTCTRL_BORDER_Y 0 // Unremovable border of native textctrl. #define wxPG_NAT_BUTTON_BORDER_ANY 0 #define wxPG_NAT_BUTTON_BORDER_X 0 #define wxPG_NAT_BUTTON_BORDER_Y 0 // Backported from wx2.9 by Julian Smart (old value was 3) #define wxPG_TEXTCTRLYADJUST 0 #else // defaults #define wxPG_CHECKMARK_XADJ 0 #define wxPG_CHECKMARK_YADJ 0 #define wxPG_CHECKMARK_WADJ 0 #define wxPG_CHECKMARK_HADJ 0 #define wxPG_CHECKMARK_DEFLATE 0 #define wxPG_NAT_TEXTCTRL_BORDER_X 0 // Unremovable border of native textctrl. #define wxPG_NAT_TEXTCTRL_BORDER_Y 0 // Unremovable border of native textctrl. #define wxPG_NAT_BUTTON_BORDER_ANY 0 #define wxPG_NAT_BUTTON_BORDER_X 0 #define wxPG_NAT_BUTTON_BORDER_Y 0 #define wxPG_TEXTCTRLYADJUST 0 #endif #if (!wxPG_NAT_TEXTCTRL_BORDER_X && !wxPG_NAT_TEXTCTRL_BORDER_Y) #define wxPG_ENABLE_CLIPPER_WINDOW 0 #else #define wxPG_ENABLE_CLIPPER_WINDOW 1 #endif // for odcombo #ifdef __WXMAC__ // Backported from wx2.9 by Julian Smart // required because wxComboCtrl reserves 3pixels for wxTextCtrl's // focus ring. #define wxPG_CHOICEXADJUST -3 #define wxPG_CHOICEYADJUST -3 #else #define wxPG_CHOICEXADJUST 0 #define wxPG_CHOICEYADJUST 0 #endif // // Number added to image width for SetCustomPaintWidth // NOTE: Use different custom paint margin because of better textctrl spacing #define ODCB_CUST_PAINT_MARGIN_RO 6 #define ODCB_CUST_PAINT_MARGIN 8 // Milliseconds to wait for two mouse-ups after focus inorder // to trigger a double-click. #define DOUBLE_CLICK_CONVERSION_TRESHOLD 500 // ----------------------------------------------------------------------- // wxPGEditor // ----------------------------------------------------------------------- IMPLEMENT_ABSTRACT_CLASS(wxPGEditor, wxObject) wxPGEditor::~wxPGEditor() { } /*wxPGCellRenderer* wxPGEditor::GetCellRenderer() const { return &g_wxPGDefaultRenderer; }*/ void wxPGEditor::DrawValue( wxDC& dc, const wxRect& rect, wxPGProperty* property, const wxString& text ) const { if ( !property->IsValueUnspecified() ) dc.DrawText( text, rect.x+wxPG_XBEFORETEXT, rect.y ); } #if 1 // defined(__WXPYTHON__) bool wxPGEditor::GetValueFromControl( wxVariant&, wxPGProperty*, wxWindow* ) const { return false; } wxPGVariantAndBool wxPGEditor::PyGetValueFromControl( wxPGProperty* property, wxWindow* ctrl ) const { wxPGVariantAndBool vab; vab.m_result = GetValueFromControl(vab.m_value, property, ctrl); if ( vab.m_result ) vab.m_valueValid = true; return vab; } #endif void wxPGEditor::SetControlStringValue( wxPGProperty* WXUNUSED(property), wxWindow*, const wxString& ) const { } void wxPGEditor::SetControlIntValue( wxPGProperty* WXUNUSED(property), wxWindow*, int ) const { } int wxPGEditor::InsertItem( wxWindow*, const wxString&, int ) const { return -1; } void wxPGEditor::DeleteItem( wxWindow*, int ) const { return; } void wxPGEditor::OnFocus( wxPGProperty*, wxWindow* ) const { } bool wxPGEditor::CanContainCustomImage() const { return false; } // ----------------------------------------------------------------------- // wxPGClipperWindow // ----------------------------------------------------------------------- #if wxPG_ENABLE_CLIPPER_WINDOW // // Clipper window is used to "remove" borders from controls // which otherwise insist on having them despite of supplied // wxNO_BORDER window style. // class wxPGClipperWindow : public wxWindow { DECLARE_CLASS(wxPGClipperWindow) public: wxPGClipperWindow() : wxWindow() { wxPGClipperWindow::Init(); } wxPGClipperWindow(wxWindow* parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize) { Init(); Create(parent,id,pos,size); } void Create(wxWindow* parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize); virtual ~wxPGClipperWindow(); virtual bool ProcessEvent(wxEvent& event); inline wxWindow* GetControl() const { return m_ctrl; } // This is called before wxControl is constructed. void GetControlRect( int xadj, int yadj, wxPoint& pt, wxSize& sz ); // This is caleed after wxControl has been constructed. void SetControl( wxWindow* ctrl ); virtual void Refresh( bool eraseBackground = true, const wxRect *rect = (const wxRect *) NULL ); virtual void SetFocus(); virtual bool SetFont(const wxFont& font); virtual bool SetForegroundColour(const wxColour& col) { bool res = wxWindow::SetForegroundColour(col); if ( m_ctrl ) m_ctrl->SetForegroundColour(col); return res; } virtual bool SetBackgroundColour(const wxColour& col) { bool res = wxWindow::SetBackgroundColour(col); if ( m_ctrl ) m_ctrl->SetBackgroundColour(col); return res; } inline int GetXClip() const { return m_xadj; } inline int GetYClip() const { return m_yadj; } protected: wxWindow* m_ctrl; int m_xadj; // Horizontal border clip. int m_yadj; // Vertical border clip. private: void Init () { m_ctrl = (wxWindow*) NULL; } }; IMPLEMENT_CLASS(wxPGClipperWindow,wxWindow) // This is called before wxControl is constructed. void wxPGClipperWindow::GetControlRect( int xadj, int yadj, wxPoint& pt, wxSize& sz ) { m_xadj = xadj; m_yadj = yadj; pt.x = -xadj; pt.y = -yadj; wxSize own_size = GetSize(); sz.x = own_size.x+(xadj*2); sz.y = own_size.y+(yadj*2); } // This is caleed after wxControl has been constructed. void wxPGClipperWindow::SetControl( wxWindow* ctrl ) { m_ctrl = ctrl; // GTK requires this. ctrl->SetSizeHints(3,3); // Correct size of this window to match the child. wxSize sz = GetSize(); wxSize chsz = ctrl->GetSize(); int hei_adj = chsz.y - (sz.y+(m_yadj*2)); if ( hei_adj ) SetSize(sz.x,chsz.y-(m_yadj*2)); } void wxPGClipperWindow::Refresh( bool eraseBackground, const wxRect *rect ) { wxWindow::Refresh(false,rect); if ( m_ctrl ) m_ctrl->Refresh(eraseBackground); } // Pass focus to control void wxPGClipperWindow::SetFocus() { if ( m_ctrl ) m_ctrl->SetFocus(); else wxWindow::SetFocus(); } bool wxPGClipperWindow::SetFont(const wxFont& font) { bool res = wxWindow::SetFont(font); if ( m_ctrl ) return m_ctrl->SetFont(font); return res; } void wxPGClipperWindow::Create(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size ) { wxWindow::Create(parent,id,pos,size); } wxPGClipperWindow::~wxPGClipperWindow() { } bool wxPGClipperWindow::ProcessEvent(wxEvent& event) { if ( event.GetEventType() == wxEVT_SIZE ) { if ( m_ctrl ) { // Maintain correct size relationship. wxSize sz = GetSize(); m_ctrl->SetSize(sz.x+(m_xadj*2),sz.y+(m_yadj*2)); event.Skip(); return false; } } return wxWindow::ProcessEvent(event); } #endif // wxPG_ENABLE_CLIPPER_WINDOW /*wxWindow* wxPropertyGrid::GetActualEditorControl( wxWindow* ctrl ) { #if wxPG_ENABLE_CLIPPER_WINDOW // Pass real control instead of clipper window if ( ctrl->IsKindOf(CLASSINFO(wxPGClipperWindow)) ) { return ((wxPGClipperWindow*)ctrl)->GetControl(); } #else return ctrl; #endif }*/ // ----------------------------------------------------------------------- // wxPGTextCtrlEditor // ----------------------------------------------------------------------- // Clipper window support macro (depending on whether it is used // for this editor or not) #if wxPG_NAT_TEXTCTRL_BORDER_X || wxPG_NAT_TEXTCTRL_BORDER_Y #define wxPG_NAT_TEXTCTRL_BORDER_ANY 1 #else #define wxPG_NAT_TEXTCTRL_BORDER_ANY 0 #endif WX_PG_IMPLEMENT_EDITOR_CLASS(TextCtrl,wxPGTextCtrlEditor,wxPGEditor) wxPGWindowList wxPGTextCtrlEditor::CreateControls( wxPropertyGrid* propGrid, wxPGProperty* property, const wxPoint& pos, const wxSize& sz ) const { wxString text; // // If has children, and limited editing is specified, then don't create. if ( (property->GetFlags() & wxPG_PROP_NOEDITOR) && property->GetChildCount() ) return (wxWindow*) NULL; if ( !property->IsValueUnspecified() ) { int flags = property->HasFlag(wxPG_PROP_READONLY) ? 0 : wxPG_EDITABLE_VALUE; text = property->GetValueString(flags); } else { text = propGrid->GetUnspecifiedValueText(); } int flags = 0; if ( (property->GetFlags() & wxPG_PROP_PASSWORD) && property->IsKindOf(WX_PG_CLASSINFO(wxStringProperty)) ) flags |= wxTE_PASSWORD; wxWindow* wnd = propGrid->GenerateEditorTextCtrl(pos,sz,text,(wxWindow*)NULL,flags, property->GetMaxLength()); return wnd; } #if 0 void wxPGTextCtrlEditor::DrawValue( wxDC& dc, wxPGProperty* property, const wxRect& rect ) const { if ( !property->IsValueUnspecified() ) { wxString drawStr = property->GetDisplayedString(); // Code below should no longer be needed, as the obfuscation // is now done in GetValueAsString. /*if ( (property->GetFlags() & wxPG_PROP_PASSWORD) && property->IsKindOf(WX_PG_CLASSINFO(wxStringProperty)) ) { size_t a = drawStr.length(); drawStr.Empty(); drawStr.Append(wxT('*'),a); }*/ dc.DrawText( drawStr, rect.x+wxPG_XBEFORETEXT, rect.y ); } } #endif void wxPGTextCtrlEditor::UpdateControl( wxPGProperty* property, wxWindow* ctrl ) const { wxTextCtrl* tc = wxStaticCast(ctrl, wxTextCtrl); wxString s; if ( tc->HasFlag(wxTE_PASSWORD) ) s = property->GetValueAsString(wxPG_FULL_VALUE); else s = property->GetDisplayedString(); wxPropertyGrid* pg = property->GetGrid(); pg->SetupTextCtrlValue(s); tc->SetValue(s); // Must always fix indentation, just in case #if defined(__WXMSW__) && !defined(__WXWINCE__) ::SendMessage(GetHwndOf(tc), EM_SETMARGINS, EC_LEFTMARGIN | EC_RIGHTMARGIN, MAKELONG(0, 0)); #endif } // Provided so that, for example, ComboBox editor can use the same code // (multiple inheritance would get way too messy). bool wxPGTextCtrlEditor::OnTextCtrlEvent( wxPropertyGrid* propGrid, wxPGProperty* WXUNUSED(property), wxWindow* ctrl, wxEvent& event ) { if ( !ctrl ) return false; if ( event.GetEventType() == wxEVT_COMMAND_TEXT_ENTER ) { if ( propGrid->IsEditorsValueModified() ) { return true; } } else if ( event.GetEventType() == wxEVT_COMMAND_TEXT_UPDATED ) { // // Pass this event outside wxPropertyGrid so that, // if necessary, program can tell when user is editing // a textctrl. // FIXME: Is it safe to change event id in the middle of event // processing (seems to work, but...)? event.Skip(); event.SetId(propGrid->GetId()); propGrid->EditorsValueWasModified(); } return false; } bool wxPGTextCtrlEditor::OnEvent( wxPropertyGrid* propGrid, wxPGProperty* property, wxWindow* ctrl, wxEvent& event ) const { return wxPGTextCtrlEditor::OnTextCtrlEvent(propGrid,property,ctrl,event); } bool wxPGTextCtrlEditor::GetTextCtrlValueFromControl( wxVariant& variant, wxPGProperty* property, wxWindow* ctrl ) { wxTextCtrl* tc = wxStaticCast(ctrl, wxTextCtrl); wxString textVal = tc->GetValue(); if ( property->UsesAutoUnspecified() && !textVal.length() ) { variant.MakeNull(); return true; } bool res = property->ActualStringToValue(variant, textVal, wxPG_EDITABLE_VALUE); // Changing unspecified always causes event (returning // true here should be enough to trigger it). // TODO: Move to propgrid.cpp if ( !res && variant.IsNull() ) res = true; return res; } bool wxPGTextCtrlEditor::GetValueFromControl( wxVariant& variant, wxPGProperty* property, wxWindow* ctrl ) const { return wxPGTextCtrlEditor::GetTextCtrlValueFromControl(variant, property, ctrl); } void wxPGTextCtrlEditor::SetValueToUnspecified( wxPGProperty* property, wxWindow* ctrl ) const { wxTextCtrl* tc = wxStaticCast(ctrl, wxTextCtrl); wxPropertyGrid* pg = property->GetGrid(); wxASSERT(pg); // Really, property grid should exist if editor does if ( pg ) { wxString tcText = pg->GetUnspecifiedValueText(); pg->SetupTextCtrlValue(tcText); tc->SetValue(tcText); } } void wxPGTextCtrlEditor::SetControlStringValue( wxPGProperty* property, wxWindow* ctrl, const wxString& txt ) const { wxTextCtrl* tc = wxStaticCast(ctrl, wxTextCtrl); wxPropertyGrid* pg = property->GetGrid(); wxASSERT(pg); // Really, property grid should exist if editor does if ( pg ) tc->SetValue(txt); } void wxPGTextCtrlEditor_OnFocus( wxPGProperty* property, wxTextCtrl*tc ) { // Make sure there is correct text (instead of unspecified value // indicator or inline help) int flags = property->HasFlag(wxPG_PROP_READONLY) ? 0 : wxPG_EDITABLE_VALUE; wxString correctText = property->GetValueString(flags); if ( tc->GetValue() != correctText ) { property->GetGrid()->SetupTextCtrlValue(correctText); tc->SetValue(correctText); } tc->SetSelection(-1,-1); } void wxPGTextCtrlEditor::OnFocus( wxPGProperty* property, wxWindow* wnd ) const { wxTextCtrl* tc = wxStaticCast(wnd, wxTextCtrl); wxPGTextCtrlEditor_OnFocus(property, tc); } wxPGTextCtrlEditor::~wxPGTextCtrlEditor() { // Reset the global pointer. Useful when wxPropertyGrid is accessed // from an external main loop. wxPG_EDITOR(TextCtrl) = NULL; } // ----------------------------------------------------------------------- // wxPGChoiceEditor // ----------------------------------------------------------------------- WX_PG_IMPLEMENT_EDITOR_CLASS(Choice,wxPGChoiceEditor,wxPGEditor) // This is a special enhanced double-click processor class. // In essence, it allows for double-clicks for which the // first click "created" the control. class wxPGDoubleClickProcessor : public wxEvtHandler { public: wxPGDoubleClickProcessor( wxPGOwnerDrawnComboBox* combo ) : wxEvtHandler() { m_timeLastMouseUp = 0; m_combo = combo; m_downReceived = false; } protected: void OnMouseEvent( wxMouseEvent& event ) { wxLongLong t = ::wxGetLocalTimeMillis(); int evtType = event.GetEventType(); if ( m_combo->HasFlag(wxPGCC_DCLICK_CYCLES) && !m_combo->IsPopupShown() ) { // Just check that it is in the text area wxPoint pt = event.GetPosition(); if ( m_combo->GetTextRect().wxPGRectContains(pt) ) { if ( evtType == wxEVT_LEFT_DOWN ) { // Set value to avoid up-events without corresponding downs m_downReceived = true; } else if ( evtType == wxEVT_LEFT_DCLICK ) { // We'll make our own double-clicks event.SetEventType(0); return; } else if ( evtType == wxEVT_LEFT_UP ) { if ( m_downReceived || m_timeLastMouseUp == 1 ) { wxLongLong timeFromLastUp = (t-m_timeLastMouseUp); if ( timeFromLastUp < DOUBLE_CLICK_CONVERSION_TRESHOLD ) { event.SetEventType(wxEVT_LEFT_DCLICK); m_timeLastMouseUp = 1; } else { m_timeLastMouseUp = t; } } } } } event.Skip(); } void OnSetFocus( wxFocusEvent& event ) { m_timeLastMouseUp = ::wxGetLocalTimeMillis(); event.Skip(); } private: wxLongLong m_timeLastMouseUp; wxPGOwnerDrawnComboBox* m_combo; bool m_downReceived; DECLARE_EVENT_TABLE() }; BEGIN_EVENT_TABLE(wxPGDoubleClickProcessor, wxEvtHandler) EVT_MOUSE_EVENTS(wxPGDoubleClickProcessor::OnMouseEvent) EVT_SET_FOCUS(wxPGDoubleClickProcessor::OnSetFocus) END_EVENT_TABLE() class wxPGComboBox : public wxPGOwnerDrawnComboBox { public: wxPGComboBox() : wxPGOwnerDrawnComboBox() { m_dclickProcessor = (wxPGDoubleClickProcessor*) NULL; m_sizeEventCalled = false; } ~wxPGComboBox() { if ( m_dclickProcessor ) { RemoveEventHandler(m_dclickProcessor); delete m_dclickProcessor; } } bool Create(wxWindow *parent, wxWindowID id, const wxString& value, const wxPoint& pos, const wxSize& size, const wxArrayString& choices, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxT("wxOwnerDrawnComboBox")) { if ( !wxPGOwnerDrawnComboBox::Create( parent, id, value, pos, size, choices, style, validator, name ) ) return false; m_dclickProcessor = new wxPGDoubleClickProcessor(this); PushEventHandler(m_dclickProcessor); return true; } #if wxPG_USING_WXOWNERDRAWNCOMBOBOX virtual void OnDrawItem( wxDC& dc, const wxRect& rect, int item, int flags ) const #else virtual bool OnDrawItem( wxDC& dc, const wxRect& rect, int item, int flags ) const #endif { wxPropertyGrid* pg = GetGrid(); pg->OnComboItemPaint((wxPGCustomComboControl*)this,item,dc,(wxRect&)rect,flags); #if !wxPG_USING_WXOWNERDRAWNCOMBOBOX return true; #endif } virtual wxCoord OnMeasureItem( size_t item ) const { wxPropertyGrid* pg = GetGrid(); wxRect rect; rect.x = -1; rect.width = 0; pg->OnComboItemPaint((wxPGCustomComboControl*)this,item,*((wxDC*)NULL),rect,0); return rect.height; } wxPropertyGrid* GetGrid() const { wxPropertyGrid* pg = wxDynamicCast(GetParent()->GetParent(),wxPropertyGrid); wxASSERT(pg); return pg; } virtual wxCoord OnMeasureItemWidth( size_t item ) const { wxPropertyGrid* pg = GetGrid(); wxRect rect; rect.x = -1; rect.width = -1; pg->OnComboItemPaint((wxPGCustomComboControl*)this,item,*((wxDC*)NULL),rect,0); return rect.width; } virtual void PositionTextCtrl( int WXUNUSED(textCtrlXAdjust), int WXUNUSED(textCtrlYAdjust) ) { wxPropertyGrid* pg = GetGrid(); wxPGOwnerDrawnComboBox::PositionTextCtrl( wxPG_TEXTCTRLXADJUST - (wxPG_XBEFOREWIDGET+wxPG_CONTROL_MARGIN+1) - 1, pg->GetSpacingY() + 2 ); } private: wxPGDoubleClickProcessor* m_dclickProcessor; bool m_sizeEventCalled; }; void wxPropertyGrid::OnComboItemPaint( wxPGCustomComboControl* pCc, int item, wxDC& dc, wxRect& rect, int flags ) { wxPGComboBox* pCb = (wxPGComboBox*)pCc; // Sanity check wxASSERT( IsKindOf(CLASSINFO(wxPropertyGrid)) ); wxPGProperty* p = GetSelection(); wxString text; const wxPGChoices* pChoices = &p->GetChoices(); const wxPGCommonValue* comVal = NULL; int choiceCount = p->GetChoiceCount(); int comVals = p->GetDisplayedCommonValueCount(); int comValIndex = -1; if ( item >= choiceCount && comVals > 0 ) { comValIndex = item - choiceCount; comVal = GetCommonValue(comValIndex); if ( !p->IsValueUnspecified() ) text = comVal->GetLabel(); } else { if ( !(flags & wxPGCC_PAINTING_CONTROL) ) { text = pCb->GetString(item); } else { if ( !p->IsValueUnspecified() ) text = p->GetValueString(0); } } if ( item < 0 ) return; #if !wxPG_USING_WXOWNERDRAWNCOMBOBOX // Add wxPGCC_PAINTING_SELECTED if ( !(flags & wxPGCC_PAINTING_CONTROL) && wxDynamicCast(pCb->GetPopup()->GetControl(),wxVListBox)->GetSelection() == item ) flags |= wxPGCC_PAINTING_SELECTED; #endif wxSize cis; const wxBitmap* itemBitmap = NULL; if ( item >= 0 && pChoices && pChoices->Item(item).GetBitmap().Ok() && comValIndex == -1 ) itemBitmap = &pChoices->Item(item).GetBitmap(); // // Decide what custom image size to use if ( itemBitmap ) { cis.x = itemBitmap->GetWidth(); cis.y = itemBitmap->GetHeight(); } else { cis = GetImageSize(p, item); } if ( rect.x < 0 ) { // Default measure behaviour (no flexible, custom paint image only) if ( rect.width < 0 ) { wxCoord x, y; GetTextExtent(text, &x, &y, 0, 0); rect.width = cis.x + wxCC_CUSTOM_IMAGE_MARGIN1 + wxCC_CUSTOM_IMAGE_MARGIN2 + 9 + x; } rect.height = cis.y + 2; return; } wxPGPaintData paintdata; paintdata.m_parent = NULL; paintdata.m_choiceItem = item; // This is by the current (1.0.0b) spec - if painting control, item is -1 if ( (flags & wxPGCC_PAINTING_CONTROL) ) paintdata.m_choiceItem = -1; if ( &dc ) dc.SetBrush(*wxWHITE_BRUSH); wxPGCellRenderer* renderer = NULL; const wxPGCell* cell = NULL; if ( rect.x >= 0 ) { // // DrawItem call wxPoint pt(rect.x + wxPG_CONTROL_MARGIN - wxPG_CHOICEXADJUST - 1, rect.y + 1); int renderFlags = 0; if ( flags & wxPGCC_PAINTING_CONTROL ) { renderFlags |= wxPGCellRenderer::Control; } else { // For consistency, always use normal font when drawing drop down // items dc.SetFont(GetFont()); } if ( flags & wxPGCC_PAINTING_SELECTED ) renderFlags |= wxPGCellRenderer::Selected; if ( cis.x > 0 && (p->HasFlag(wxPG_PROP_CUSTOMIMAGE) || !(flags & wxPGCC_PAINTING_CONTROL)) && ( !p->m_valueBitmap || item == pCb->GetSelection() ) && ( item >= 0 || (flags & wxPGCC_PAINTING_CONTROL) ) && !itemBitmap ) { pt.x += wxCC_CUSTOM_IMAGE_MARGIN1; wxRect r(pt.x,pt.y,cis.x,cis.y); if ( flags & wxPGCC_PAINTING_CONTROL ) { //r.width = cis.x; r.height = wxPG_STD_CUST_IMAGE_HEIGHT(m_lineHeight); } paintdata.m_drawnWidth = r.width; dc.SetPen(m_colPropFore); if ( comValIndex >= 0 ) { const wxPGCommonValue* cv = GetCommonValue(comValIndex); wxPGCellRenderer* renderer = cv->GetRenderer(); r.width = rect.width; renderer->Render( dc, r, this, p, m_selColumn, comValIndex, renderFlags ); return; } else if ( item >= 0 ) { p->OnCustomPaint( dc, r, paintdata ); } else { dc.DrawRectangle( r ); } pt.x += paintdata.m_drawnWidth + wxCC_CUSTOM_IMAGE_MARGIN2 - 1; } else { // TODO: This aligns text so that it seems to be horizontally // on the same line as property values. Not really // sure if its needed, but seems to not cause any harm. pt.x -= 1; if ( (flags & wxPGCC_PAINTING_CONTROL) ) { if ( p->IsValueUnspecified() ) cell = &m_unspecifiedAppearance; else if ( item < 0 ) item = pCb->GetSelection(); } if ( p->IsValueUnspecified() && item < 0 ) { cell = &m_unspecifiedAppearance; } if ( pChoices && item >= 0 && comValIndex < 0 ) { cell = &pChoices->Item(item); renderer = wxPGGlobalVars->m_defaultRenderer; int imageOffset = renderer->PreDrawCell(dc, rect, *cell, renderFlags ); if ( imageOffset ) imageOffset += wxCC_CUSTOM_IMAGE_MARGIN1 + wxCC_CUSTOM_IMAGE_MARGIN2; pt.x += imageOffset; } } // // Draw text // pt.y += (rect.height-m_fontHeight)/2 - 1; pt.x += 1; dc.DrawText( text, pt.x + wxPG_XBEFORETEXT, pt.y ); if ( renderer ) renderer->PostDrawCell(dc, this, *cell, renderFlags); } else { // // MeasureItem call p->OnCustomPaint( dc, rect, paintdata ); rect.height = paintdata.m_drawnHeight + 2; rect.width = cis.x + wxCC_CUSTOM_IMAGE_MARGIN1 + wxCC_CUSTOM_IMAGE_MARGIN2 + 9; } } bool wxPGChoiceEditor_SetCustomPaintWidth( wxPropertyGrid* propGrid, wxPGComboBox* cb, wxPGProperty* property, int cmnVal ) { // Must return true if value was not a common value int custPaintMargin; // // Use different custom paint margin because of better textctrl spacing if ( cb->HasFlag(wxCB_READONLY) ) custPaintMargin = ODCB_CUST_PAINT_MARGIN_RO; else custPaintMargin = ODCB_CUST_PAINT_MARGIN; if ( property->IsValueUnspecified() ) { cb->SetCustomPaintWidth( 0 ); return true; } if ( cmnVal >= 0 ) { // Yes, a common value is being selected property->SetCommonValue( cmnVal ); wxSize imageSize = propGrid->GetCommonValue(cmnVal)-> GetRenderer()->GetImageSize(property, 1, cmnVal); if ( imageSize.x ) imageSize.x += custPaintMargin; cb->SetCustomPaintWidth( imageSize.x ); return false; } else { wxSize imageSize = propGrid->GetImageSize(property, -1); if ( imageSize.x ) imageSize.x += custPaintMargin; cb->SetCustomPaintWidth( imageSize.x ); return true; } } // CreateControls calls this with CB_READONLY in extraStyle wxWindow* wxPGChoiceEditor::CreateControlsBase( wxPropertyGrid* propGrid, wxPGProperty* property, const wxPoint& pos, const wxSize& sz, long extraStyle ) const { wxString defString; // Since it is not possible (yet) to create a read-only combo box in // the same sense that wxTextCtrl is read-only, simply do not create // the control in this case. if ( property->HasFlag(wxPG_PROP_READONLY) ) return NULL; // Get choices. int index = property->GetChoiceInfo( NULL ); bool isUnspecified = property->IsValueUnspecified(); if ( isUnspecified ) index = -1; else defString = property->GetDisplayedString(); const wxPGChoices& choices = property->GetChoices(); wxArrayString labels = choices.GetLabels(); wxPGComboBox* cb; wxPoint po(pos); wxSize si(sz); po.y += wxPG_CHOICEYADJUST; si.y -= (wxPG_CHOICEYADJUST*2); po.x += wxPG_CHOICEXADJUST; si.x -= wxPG_CHOICEXADJUST; wxWindow* ctrlParent = propGrid->GetPanel(); int odcbFlags = extraStyle | wxNO_BORDER | wxPGCC_PROCESS_ENTER | wxPGCC_ALT_KEYS; if ( (property->GetFlags() & wxPG_PROP_USE_DCC) && (property->IsKindOf(CLASSINFO(wxBoolProperty)) ) ) odcbFlags |= wxPGCC_DCLICK_CYCLES; // // If common value specified, use appropriate index unsigned int cmnVals = property->GetDisplayedCommonValueCount(); if ( cmnVals ) { if ( !isUnspecified ) { int cmnVal = property->GetCommonValue(); if ( cmnVal >= 0 ) { index = labels.size() + cmnVal; } } unsigned int i; for ( i=0; i<cmnVals; i++ ) labels.Add(propGrid->GetCommonValueLabel(i)); } cb = new wxPGComboBox(); #ifdef __WXMSW__ cb->Hide(); #endif cb->Create(ctrlParent, wxPG_SUBID1, wxString(), po, si, labels, odcbFlags); //int extRight = propGrid->GetClientSize().x - (po.x+si.x); //int extRight = - (po.x+si.x); cb->SetButtonPosition(si.y,0,wxRIGHT); //cb->SetPopupExtents( 1, extRight ); cb->SetTextIndent(wxPG_XBEFORETEXT-1); wxPGChoiceEditor_SetCustomPaintWidth( propGrid, cb, property, property->GetCommonValue() ); /*if ( property->GetFlags() & wxPG_PROP_CUSTOMIMAGE ) { wxSize imageSize = propGrid->GetImageSize(property, index); if ( imageSize.x ) imageSize.x += ODCB_CUST_PAINT_MARGIN; cb->SetCustomPaintWidth( imageSize.x ); }*/ if ( index >= 0 && index < (int)cb->GetCount() ) { cb->SetSelection( index ); if ( defString.length() ) cb->SetText( defString ); } else if ( !(extraStyle & wxCB_READONLY) && defString.length() ) cb->SetValue( defString ); else cb->SetSelection( -1 ); #ifdef __WXMSW__ cb->Show(); #endif return (wxWindow*) cb; } void wxPGChoiceEditor::UpdateControl( wxPGProperty* property, wxWindow* ctrl ) const { wxASSERT( ctrl ); wxPGOwnerDrawnComboBox* cb = (wxPGOwnerDrawnComboBox*)ctrl; wxASSERT( cb->IsKindOf(CLASSINFO(wxPGOwnerDrawnComboBox))); int ind = property->GetChoiceInfo( (wxPGChoiceInfo*)NULL ); cb->SetSelection(ind); } wxPGWindowList wxPGChoiceEditor::CreateControls( wxPropertyGrid* propGrid, wxPGProperty* property, const wxPoint& pos, const wxSize& sz ) const { return CreateControlsBase(propGrid,property,pos,sz,wxCB_READONLY); } int wxPGChoiceEditor::InsertItem( wxWindow* ctrl, const wxString& label, int index ) const { wxASSERT( ctrl ); wxPGOwnerDrawnComboBox* cb = (wxPGOwnerDrawnComboBox*)ctrl; wxASSERT( cb->IsKindOf(CLASSINFO(wxPGOwnerDrawnComboBox))); if (index < 0) index = cb->GetCount(); return cb->Insert(label,index); } void wxPGChoiceEditor::DeleteItem( wxWindow* ctrl, int index ) const { wxASSERT( ctrl ); wxPGOwnerDrawnComboBox* cb = (wxPGOwnerDrawnComboBox*)ctrl; wxASSERT( cb->IsKindOf(CLASSINFO(wxPGOwnerDrawnComboBox))); cb->Delete(index); } bool wxPGChoiceEditor::OnEvent( wxPropertyGrid* propGrid, wxPGProperty* property, wxWindow* ctrl, wxEvent& event ) const { if ( event.GetEventType() == wxEVT_COMMAND_COMBOBOX_SELECTED ) { wxPGComboBox* cb = (wxPGComboBox*)ctrl; int index = cb->GetSelection(); int cmnValIndex = -1; int cmnVals = property->GetDisplayedCommonValueCount(); int items = cb->GetCount(); if ( index >= (items-cmnVals) ) { // Yes, a common value is being selected cmnValIndex = index - (items-cmnVals); property->SetCommonValue( cmnValIndex ); // Truly set value to unspecified? if ( propGrid->GetUnspecifiedCommonValue() == cmnValIndex ) { if ( !property->IsValueUnspecified() ) propGrid->SetInternalFlag(wxPG_FL_VALUE_CHANGE_IN_EVENT); property->SetValueToUnspecified(); if ( !cb->HasFlag(wxCB_READONLY) ) cb->GetTextCtrl()->SetValue(wxEmptyString); return false; } } return wxPGChoiceEditor_SetCustomPaintWidth( propGrid, cb, property, cmnValIndex); } return false; } bool wxPGChoiceEditor::GetValueFromControl( wxVariant& variant, wxPGProperty* property, wxWindow* ctrl ) const { wxPGOwnerDrawnComboBox* cb = (wxPGOwnerDrawnComboBox*)ctrl; int index = cb->GetSelection(); if ( index != property->GetChoiceInfo( (wxPGChoiceInfo*) NULL ) || // Changing unspecified always causes event (returning // true here should be enough to trigger it). property->IsValueUnspecified() ) { return property->ActualIntToValue( variant, index, 0 ); } return false; } void wxPGChoiceEditor::SetControlStringValue( wxPGProperty* WXUNUSED(property), wxWindow* ctrl, const wxString& txt ) const { wxPGOwnerDrawnComboBox* cb = (wxPGOwnerDrawnComboBox*)ctrl; wxASSERT( cb ); cb->SetValue(txt); } void wxPGChoiceEditor::SetControlIntValue( wxPGProperty* WXUNUSED(property), wxWindow* ctrl, int value ) const { wxPGOwnerDrawnComboBox* cb = (wxPGOwnerDrawnComboBox*)ctrl; wxASSERT( cb ); cb->SetSelection(value); } void wxPGChoiceEditor::SetValueToUnspecified( wxPGProperty* property, wxWindow* ctrl ) const { wxPGOwnerDrawnComboBox* cb = (wxPGOwnerDrawnComboBox*)ctrl; if ( !cb->HasFlag(wxCB_READONLY) ) { wxPropertyGrid* pg = property->GetGrid(); if ( pg ) { wxString tcText = pg->GetUnspecifiedValueText(); pg->SetupTextCtrlValue(tcText); cb->SetValue(tcText); } } else { cb->SetSelection(-1); } } bool wxPGChoiceEditor::CanContainCustomImage() const { return true; } wxPGChoiceEditor::~wxPGChoiceEditor() { // Reset the global pointer. Useful when wxPropertyGrid is accessed // from an external main loop. wxPG_EDITOR(Choice) = NULL; } // ----------------------------------------------------------------------- // wxPGComboBoxEditor // ----------------------------------------------------------------------- WX_PG_IMPLEMENT_EDITOR_CLASS(ComboBox,wxPGComboBoxEditor,wxPGChoiceEditor) void wxPGComboBoxEditor::UpdateControl( wxPGProperty* property, wxWindow* ctrl ) const { wxPGOwnerDrawnComboBox* cb = (wxPGOwnerDrawnComboBox*)ctrl; cb->SetValue(property->GetValueString(wxPG_EDITABLE_VALUE)); // TODO: If string matches any selection, then select that. } wxPGWindowList wxPGComboBoxEditor::CreateControls( wxPropertyGrid* propGrid, wxPGProperty* property, const wxPoint& pos, const wxSize& sz ) const { return CreateControlsBase(propGrid,property,pos,sz,0); } bool wxPGComboBoxEditor::OnEvent( wxPropertyGrid* propGrid, wxPGProperty* property, wxWindow* ctrl, wxEvent& event ) const { wxPGOwnerDrawnComboBox* cb = (wxPGOwnerDrawnComboBox*) NULL; wxWindow* textCtrl = (wxWindow*) NULL; if ( ctrl ) { cb = (wxPGOwnerDrawnComboBox*)ctrl; textCtrl = cb->GetTextCtrl(); } if ( wxPGTextCtrlEditor::OnTextCtrlEvent(propGrid,property,textCtrl,event) ) return true; return wxPGChoiceEditor::OnEvent(propGrid,property,ctrl,event); } bool wxPGComboBoxEditor::GetValueFromControl( wxVariant& variant, wxPGProperty* property, wxWindow* ctrl ) const { wxPGOwnerDrawnComboBox* cb = (wxPGOwnerDrawnComboBox*)ctrl; wxString textVal = cb->GetValue(); if ( property->UsesAutoUnspecified() && !textVal.length() ) { variant.MakeNull(); return true; } bool res = property->ActualStringToValue(variant, textVal, wxPG_EDITABLE_VALUE); // Changing unspecified always causes event (returning // true here should be enough to trigger it). if ( !res && variant.IsNull() ) res = true; return res; } void wxPGComboBoxEditor::OnFocus( wxPGProperty* property, wxWindow* ctrl ) const { wxPGOwnerDrawnComboBox* cb = (wxPGOwnerDrawnComboBox*)ctrl; wxPGTextCtrlEditor_OnFocus(property, cb->GetTextCtrl()); } wxPGComboBoxEditor::~wxPGComboBoxEditor() { // Reset the global pointer. Useful when wxPropertyGrid is accessed // from an external main loop. wxPG_EDITOR(ComboBox) = NULL; } // ----------------------------------------------------------------------- // wxPGChoiceAndButtonEditor // ----------------------------------------------------------------------- // This simpler implement_editor macro doesn't define class body. WX_PG_IMPLEMENT_EDITOR_CLASS(ChoiceAndButton,wxPGChoiceAndButtonEditor,wxPGChoiceEditor) wxPGWindowList wxPGChoiceAndButtonEditor::CreateControls( wxPropertyGrid* propGrid, wxPGProperty* property, const wxPoint& pos, const wxSize& sz ) const { // Use one two units smaller to match size of the combo's dropbutton. // (normally a bigger button is used because it looks better) int bt_wid = sz.y; bt_wid -= 2; wxSize bt_sz(bt_wid,bt_wid); // Position of button. wxPoint bt_pos(pos.x+sz.x-bt_sz.x,pos.y); #ifdef __WXMAC__ bt_pos.y -= 1; #else bt_pos.y += 1; #endif wxWindow* bt = propGrid->GenerateEditorButton( bt_pos, bt_sz ); // Size of choice. wxSize ch_sz(sz.x-bt->GetSize().x,sz.y); #ifdef __WXMAC__ ch_sz.x -= wxPG_TEXTCTRL_AND_BUTTON_SPACING; #endif wxWindow* ch = wxPG_EDITOR(Choice)->CreateControls(propGrid,property, pos,ch_sz).m_primary; #ifdef __WXMSW__ bt->Show(); #endif return wxPGWindowList(ch, bt); } wxPGChoiceAndButtonEditor::~wxPGChoiceAndButtonEditor() { // Reset the global pointer. Useful when wxPropertyGrid is accessed // from an external main loop. wxPG_EDITOR(ChoiceAndButton) = NULL; } // ----------------------------------------------------------------------- // wxPGTextCtrlAndButtonEditor // ----------------------------------------------------------------------- // This simpler implement_editor macro doesn't define class body. WX_PG_IMPLEMENT_EDITOR_CLASS(TextCtrlAndButton,wxPGTextCtrlAndButtonEditor,wxPGTextCtrlEditor) wxPGWindowList wxPGTextCtrlAndButtonEditor::CreateControls( wxPropertyGrid* propGrid, wxPGProperty* property, const wxPoint& pos, const wxSize& sz ) const { wxWindow* wnd2; wxWindow* wnd = propGrid->GenerateEditorTextCtrlAndButton( pos, sz, &wnd2, property->GetFlags() & wxPG_PROP_NOEDITOR, property); return wxPGWindowList(wnd, wnd2); } wxPGTextCtrlAndButtonEditor::~wxPGTextCtrlAndButtonEditor() { // Reset the global pointer. Useful when wxPropertyGrid is accessed // from an external main loop. wxPG_EDITOR(TextCtrlAndButton) = NULL; } // ----------------------------------------------------------------------- // wxPGCheckBoxEditor // ----------------------------------------------------------------------- #if wxPG_INCLUDE_CHECKBOX WX_PG_IMPLEMENT_EDITOR_CLASS(CheckBox,wxPGCheckBoxEditor,wxPGEditor) // Check box state flags enum { wxSCB_STATE_UNCHECKED = 0, wxSCB_STATE_CHECKED = 1, wxSCB_STATE_BOLD = 2, wxSCB_STATE_UNSPECIFIED = 4 }; const int wxSCB_SETVALUE_CYCLE = 2; static void DrawSimpleCheckBox( wxDC& dc, const wxRect& rect, int box_hei, int state ) { // Box rectangle. wxRect r(rect.x+wxPG_XBEFORETEXT,rect.y+((rect.height-box_hei)/2), box_hei,box_hei); wxColour useCol = dc.GetTextForeground(); // Draw check mark first because it is likely to overdraw the // surrounding rectangle. if ( state & wxSCB_STATE_CHECKED ) { wxRect r2(r.x+wxPG_CHECKMARK_XADJ, r.y+wxPG_CHECKMARK_YADJ, r.width+wxPG_CHECKMARK_WADJ, r.height+wxPG_CHECKMARK_HADJ); #if wxPG_CHECKMARK_DEFLATE r2.Deflate(wxPG_CHECKMARK_DEFLATE); #endif dc.DrawCheckMark(r2); // This would draw a simple cross check mark. // dc.DrawLine(r.x,r.y,r.x+r.width-1,r.y+r.height-1); // dc.DrawLine(r.x,r.y+r.height-1,r.x+r.width-1,r.y); } if ( !(state & wxSCB_STATE_BOLD) ) { // Pen for thin rectangle. dc.SetPen(useCol); } else { // Pen for bold rectangle. wxPen linepen(useCol,2,wxSOLID); linepen.SetJoin(wxJOIN_MITER); // This prevents round edges. dc.SetPen(linepen); r.x++; r.y++; r.width--; r.height--; } dc.SetBrush(*wxTRANSPARENT_BRUSH); dc.DrawRectangle(r); dc.SetPen(*wxTRANSPARENT_PEN); } // // Real simple custom-drawn checkbox-without-label class. // class wxSimpleCheckBox : public wxControl { public: void SetValue( int value ); wxSimpleCheckBox( wxWindow* parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize ) : wxControl(parent,id,pos,size,wxNO_BORDER|wxWANTS_CHARS) { // Due to SetOwnFont stuff necessary for GTK+ 1.2, we need to have this SetFont( parent->GetFont() ); m_state = wxSCB_STATE_UNCHECKED; wxPropertyGrid* pg = (wxPropertyGrid*) parent->GetParent(); wxASSERT( pg->IsKindOf(CLASSINFO(wxPropertyGrid)) ); m_boxHeight = pg->GetFontHeight(); SetBackgroundStyle( wxBG_STYLE_COLOUR ); } virtual ~wxSimpleCheckBox(); virtual bool ProcessEvent(wxEvent& event); int m_state; int m_boxHeight; static wxBitmap* ms_doubleBuffer; }; wxSimpleCheckBox::~wxSimpleCheckBox() { delete ms_doubleBuffer; ms_doubleBuffer = NULL; } wxBitmap* wxSimpleCheckBox::ms_doubleBuffer = (wxBitmap*) NULL; void wxSimpleCheckBox::SetValue( int value ) { if ( value == wxSCB_SETVALUE_CYCLE ) { if ( m_state & wxSCB_STATE_CHECKED ) m_state &= ~wxSCB_STATE_CHECKED; else m_state |= wxSCB_STATE_CHECKED; } else { m_state = value; } Refresh(); wxCommandEvent evt(wxEVT_COMMAND_CHECKBOX_CLICKED,GetParent()->GetId()); wxPropertyGrid* propGrid = (wxPropertyGrid*) GetParent()->GetParent(); wxASSERT( propGrid->IsKindOf(CLASSINFO(wxPropertyGrid)) ); propGrid->OnCustomEditorEvent(evt); } bool wxSimpleCheckBox::ProcessEvent(wxEvent& event) { wxPropertyGrid* propGrid = (wxPropertyGrid*) GetParent()->GetParent(); wxASSERT( propGrid->IsKindOf(CLASSINFO(wxPropertyGrid)) ); if ( event.GetEventType() == wxEVT_NAVIGATION_KEY ) { //wxLogDebug(wxT("wxEVT_NAVIGATION_KEY")); //SetFocusFromKbd(); //event.Skip(); //return wxControl::ProcessEvent(event); } else if ( ( (event.GetEventType() == wxEVT_LEFT_DOWN || event.GetEventType() == wxEVT_LEFT_DCLICK) && ((wxMouseEvent&)event).m_x > (wxPG_XBEFORETEXT-2) && ((wxMouseEvent&)event).m_x <= (wxPG_XBEFORETEXT-2+m_boxHeight) ) ) { SetValue(wxSCB_SETVALUE_CYCLE); return true; } else if ( event.GetEventType() == wxEVT_PAINT ) { wxSize clientSize = GetClientSize(); wxPaintDC dc(this); /* // Buffered paint DC doesn't seem to do much good if ( !ms_doubleBuffer || clientSize.x > ms_doubleBuffer->GetWidth() || clientSize.y > ms_doubleBuffer->GetHeight() ) { delete ms_doubleBuffer; ms_doubleBuffer = new wxBitmap(clientSize.x+25,clientSize.y+25); } wxBufferedPaintDC dc(this,*ms_doubleBuffer); */ wxRect rect(0,0,clientSize.x,clientSize.y); //rect.x -= 1; rect.y += 1; rect.width += 1; m_boxHeight = propGrid->GetFontHeight(); wxColour bgcol = GetBackgroundColour(); dc.SetBrush( bgcol ); dc.SetPen( bgcol ); dc.DrawRectangle( rect ); dc.SetTextForeground(GetForegroundColour()); int state = m_state; if ( !(state & wxSCB_STATE_UNSPECIFIED) && GetFont().GetWeight() == wxBOLD ) state |= wxSCB_STATE_BOLD; DrawSimpleCheckBox(dc, rect, m_boxHeight, state); return true; } else if ( event.GetEventType() == wxEVT_SIZE || event.GetEventType() == wxEVT_SET_FOCUS || event.GetEventType() == wxEVT_KILL_FOCUS ) { Refresh(); } else if ( event.GetEventType() == wxEVT_KEY_DOWN ) { wxKeyEvent& keyEv = (wxKeyEvent&) event; if ( keyEv.GetKeyCode() == WXK_TAB ) { propGrid->SendNavigationKeyEvent( keyEv.ShiftDown()?0:1 ); return true; } else if ( keyEv.GetKeyCode() == WXK_SPACE ) { SetValue(wxSCB_SETVALUE_CYCLE); return true; } } return wxControl::ProcessEvent(event); } wxPGWindowList wxPGCheckBoxEditor::CreateControls( wxPropertyGrid* propGrid, wxPGProperty* property, const wxPoint& pos, const wxSize& size ) const { if ( property->HasFlag(wxPG_PROP_READONLY) ) return NULL; wxPoint pt = pos; pt.x -= wxPG_XBEFOREWIDGET; wxSize sz = size; sz.x = propGrid->GetFontHeight() + (wxPG_XBEFOREWIDGET*2) + 4; wxSimpleCheckBox* cb = new wxSimpleCheckBox(propGrid->GetPanel(),wxPG_SUBID1,pt,sz); cb->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)); cb->Connect( wxPG_SUBID1, wxEVT_LEFT_DOWN, (wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) &wxPropertyGrid::OnCustomEditorEvent, NULL, propGrid ); cb->Connect( wxPG_SUBID1, wxEVT_LEFT_DCLICK, (wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) &wxPropertyGrid::OnCustomEditorEvent, NULL, propGrid ); if ( property->IsValueUnspecified() ) { cb->m_state = wxSCB_STATE_UNSPECIFIED; } else { if ( property->GetChoiceInfo((wxPGChoiceInfo*)NULL) ) cb->m_state = wxSCB_STATE_CHECKED; // If mouse cursor was on the item, toggle the value now. if ( propGrid->GetInternalFlags() & wxPG_FL_ACTIVATION_BY_CLICK ) { wxPoint pt = cb->ScreenToClient(::wxGetMousePosition()); if ( pt.x <= (wxPG_XBEFORETEXT-2+cb->m_boxHeight) ) { if ( cb->m_state & wxSCB_STATE_CHECKED ) cb->m_state &= ~wxSCB_STATE_CHECKED; else cb->m_state |= wxSCB_STATE_CHECKED; // Makes sure wxPG_EVT_CHANGING etc. is sent for this initial // click propGrid->ChangePropertyValue(property, wxPGVariant_Bool(cb->m_state)); } } } propGrid->SetInternalFlag( wxPG_FL_FIXED_WIDTH_EDITOR ); return cb; } void wxPGCheckBoxEditor::DrawValue( wxDC& dc, const wxRect& rect, wxPGProperty* property, const wxString& WXUNUSED(text) ) const { int state = wxSCB_STATE_UNCHECKED; if ( !property->IsValueUnspecified() ) { state = property->GetChoiceInfo((wxPGChoiceInfo*)NULL); if ( dc.GetFont().GetWeight() == wxBOLD ) state |= wxSCB_STATE_BOLD; } else { state |= wxSCB_STATE_UNSPECIFIED; } DrawSimpleCheckBox(dc, rect, dc.GetCharHeight(), state); } void wxPGCheckBoxEditor::UpdateControl( wxPGProperty* property, wxWindow* ctrl ) const { wxSimpleCheckBox* cb = (wxSimpleCheckBox*) ctrl; wxASSERT( cb ); if ( !property->IsValueUnspecified() ) cb->m_state = property->GetChoiceInfo((wxPGChoiceInfo*)NULL); else cb->m_state = wxSCB_STATE_UNSPECIFIED; cb->Refresh(); } bool wxPGCheckBoxEditor::OnEvent( wxPropertyGrid* WXUNUSED(propGrid), wxPGProperty* WXUNUSED(property), wxWindow* WXUNUSED(ctrl), wxEvent& event ) const { if ( event.GetEventType() == wxEVT_COMMAND_CHECKBOX_CLICKED ) { return true; } return false; } bool wxPGCheckBoxEditor::GetValueFromControl( wxVariant& variant, wxPGProperty* property, wxWindow* ctrl ) const { wxSimpleCheckBox* cb = (wxSimpleCheckBox*)ctrl; int index = cb->m_state; if ( index != property->GetChoiceInfo( (wxPGChoiceInfo*) NULL ) || // Changing unspecified always causes event (returning // true here should be enough to trigger it). property->IsValueUnspecified() ) { return property->ActualIntToValue(variant, index, 0); } return false; } void wxPGCheckBoxEditor::SetControlIntValue( wxPGProperty* WXUNUSED(property), wxWindow* ctrl, int value ) const { if ( value != 0 ) value = 1; ((wxSimpleCheckBox*)ctrl)->m_state = value; ctrl->Refresh(); } void wxPGCheckBoxEditor::SetValueToUnspecified( wxPGProperty* WXUNUSED(property), wxWindow* ctrl ) const { ((wxSimpleCheckBox*)ctrl)->m_state = wxSCB_STATE_UNSPECIFIED; ctrl->Refresh(); } wxPGCheckBoxEditor::~wxPGCheckBoxEditor() { // Reset the global pointer. Useful when wxPropertyGrid is accessed // from an external main loop. wxPG_EDITOR(CheckBox) = NULL; } #endif // wxPG_INCLUDE_CHECKBOX // ----------------------------------------------------------------------- wxWindow* wxPropertyGrid::GetEditorControl() const { wxWindow* ctrl = m_wndEditor; if ( !ctrl ) return ctrl; // If it's clipper window, return its child instead #if wxPG_ENABLE_CLIPPER_WINDOW if ( ctrl->IsKindOf(CLASSINFO(wxPGClipperWindow)) ) { return ((wxPGClipperWindow*)ctrl)->GetControl(); } #endif return ctrl; } // ----------------------------------------------------------------------- wxTextCtrl* wxPropertyGrid::GetLabelEditor() const { wxWindow* tcWnd = m_labelEditor; if ( !tcWnd ) return NULL; #if wxPG_ENABLE_CLIPPER_WINDOW if ( tcWnd->IsKindOf(CLASSINFO(wxPGClipperWindow)) ) { tcWnd = ((wxPGClipperWindow*)tcWnd)->GetControl(); } #endif return wxStaticCast(tcWnd, wxTextCtrl); } // ----------------------------------------------------------------------- void wxPropertyGrid::CorrectEditorWidgetSizeX() { int secWid = 0; // Use fixed selColumn 1 for main editor widgets int newSplitterx = m_pState->DoGetSplitterPosition(0); int newWidth = newSplitterx + m_pState->m_colWidths[1]; if ( m_wndEditor2 ) { // if width change occurred, move secondary wnd by that amount wxRect r = m_wndEditor2->GetRect(); secWid = r.width; r.x = newWidth - secWid; m_wndEditor2->SetSize( r ); // if primary is textctrl, then we have to add some extra space #ifdef __WXMAC__ if ( m_wndEditor ) #else if ( m_wndEditor && m_wndEditor->IsKindOf(CLASSINFO(wxTextCtrl)) ) #endif secWid += wxPG_TEXTCTRL_AND_BUTTON_SPACING; } if ( m_wndEditor ) { wxRect r = m_wndEditor->GetRect(); r.x = newSplitterx+m_ctrlXAdjust; if ( !(m_iFlags & wxPG_FL_FIXED_WIDTH_EDITOR) ) r.width = newWidth - r.x - secWid; m_wndEditor->SetSize(r); } if ( m_wndEditor2 ) m_wndEditor2->Refresh(); } // ----------------------------------------------------------------------- void wxPropertyGrid::CorrectEditorWidgetPosY() { wxPGProperty* selected = GetSelection(); if ( selected ) { if ( m_labelEditor ) { wxRect r = GetEditorWidgetRect(selected, m_selColumn); wxPoint pos = m_labelEditor->GetPosition(); // Calculate y offset int offset = pos.y % m_lineHeight; m_labelEditor->Move(pos.x, r.y + offset); } if ( m_wndEditor || m_wndEditor2 ) { wxRect r = GetEditorWidgetRect(selected, 1); if ( m_wndEditor ) { wxPoint pos = m_wndEditor->GetPosition(); // Calculate y offset int offset = pos.y % m_lineHeight; m_wndEditor->Move(pos.x, r.y + offset); } if ( m_wndEditor2 ) { wxPoint pos = m_wndEditor2->GetPosition(); m_wndEditor2->Move(pos.x, r.y); } } } } // ----------------------------------------------------------------------- bool wxPropertyGrid::AdjustPosForClipperWindow( wxWindow* topCtrlWnd, int* x, int* y ) { #if wxPG_ENABLE_CLIPPER_WINDOW // Take clipper window into account if (topCtrlWnd->GetPosition().x < 1 && !topCtrlWnd->IsKindOf(CLASSINFO(wxPGClipperWindow))) { topCtrlWnd = topCtrlWnd->GetParent(); wxASSERT( topCtrlWnd->IsKindOf(CLASSINFO(wxPGClipperWindow)) ); *x -= ((wxPGClipperWindow*)topCtrlWnd)->GetXClip(); *y -= ((wxPGClipperWindow*)topCtrlWnd)->GetYClip(); return true; } #else wxUnusedVar(topCtrlWnd); wxUnusedVar(x); wxUnusedVar(y); #endif return false; } // ----------------------------------------------------------------------- // Fixes position of wxTextCtrl-like control (wxSpinCtrl usually // fits into that category as well). void wxPropertyGrid::FixPosForTextCtrl( wxWindow* ctrl, unsigned int forColumn, const wxPoint& offset ) { // Center the control vertically wxRect finalPos = ctrl->GetRect(); int y_adj = (m_lineHeight - finalPos.height)/2 + wxPG_TEXTCTRLYADJUST; // Prevent over-sized control int sz_dec = (y_adj + finalPos.height) - m_lineHeight; if ( sz_dec < 0 ) sz_dec = 0; finalPos.y += y_adj; finalPos.height -= (y_adj+sz_dec); int textCtrlXAdjust = wxPG_TEXTCTRLXADJUST; if ( forColumn != 1 ) textCtrlXAdjust -= 3; // magic number! finalPos.x += textCtrlXAdjust; finalPos.width -= textCtrlXAdjust; finalPos.x += offset.x; finalPos.y += offset.y; ctrl->SetSize(finalPos); } // ----------------------------------------------------------------------- wxWindow* wxPropertyGrid::GenerateEditorTextCtrl( const wxPoint& pos, const wxSize& sz, const wxString& value, wxWindow* secondary, int extraStyle, int maxLen, unsigned int forColumn ) { wxPGProperty* selected = GetSelection(); wxASSERT(selected); int tcFlags = wxTE_PROCESS_ENTER | extraStyle; if ( selected->HasFlag(wxPG_PROP_READONLY) && forColumn == 1 ) tcFlags |= wxTE_READONLY; wxPoint p(pos.x,pos.y); wxSize s(sz.x,sz.y); // Need to reduce width of text control on Mac #if defined(__WXMAC__) s.x -= 8; #endif // For label editors, trim the size to allow better splitter grabbing if ( forColumn != 1 ) s.x -= 2; // Take button into acccount if ( secondary ) { s.x -= (secondary->GetSize().x + wxPG_TEXTCTRL_AND_BUTTON_SPACING); m_iFlags &= ~(wxPG_FL_PRIMARY_FILLS_ENTIRE); } // If the height is significantly higher, then use border, and fill the rect exactly. bool hasSpecialSize = false; if ( (sz.y - m_lineHeight) > 5 ) hasSpecialSize = true; #if wxPG_NAT_TEXTCTRL_BORDER_ANY // Create clipper window wxPGClipperWindow* wnd = new wxPGClipperWindow(); #if defined(__WXMSW__) wnd->Hide(); #endif wnd->Create(GetPanel(),wxPG_SUBID1,p,s); // This generates rect of the control inside the clipper window if ( !hasSpecialSize ) wnd->GetControlRect(wxPG_NAT_TEXTCTRL_BORDER_X, wxPG_NAT_TEXTCTRL_BORDER_Y, p, s); else wnd->GetControlRect(0, 0, p, s); wxWindow* ctrlParent = wnd; #else wxWindow* ctrlParent = GetPanel(); if ( !hasSpecialSize ) tcFlags |= wxNO_BORDER; #endif wxTextCtrl* tc = new wxTextCtrl(); #if defined(__WXMSW__) && !wxPG_NAT_TEXTCTRL_BORDER_ANY tc->Hide(); #endif SetupTextCtrlValue(value); tc->Create(ctrlParent,wxPG_SUBID1,value, p, s,tcFlags); #if wxPG_NAT_TEXTCTRL_BORDER_ANY wxWindow* ed = wnd; wnd->SetControl(tc); #else wxWindow* ed = tc; #endif // Center the control vertically if ( !hasSpecialSize ) FixPosForTextCtrl(ed, forColumn); if ( forColumn != 1 ) { if ( tc != ed ) { ed->SetBackgroundColour(m_colSelBack); ed->SetForegroundColour(m_colSelFore); } tc->SetBackgroundColour(m_colSelBack); tc->SetForegroundColour(m_colSelFore); } #ifdef __WXMSW__ ed->Show(); if ( secondary ) secondary->Show(); #endif // Set maximum length if ( maxLen > 0 ) tc->SetMaxLength( maxLen ); return (wxWindow*) ed; } // ----------------------------------------------------------------------- wxWindow* wxPropertyGrid::GenerateEditorButton( const wxPoint& pos, const wxSize& sz ) { wxPGProperty* selected = GetSelection(); wxASSERT(selected); #ifdef __WXMAC__ // Decorations are chunky on Mac, and we can't make the button square, so // do things a bit differently on this platform. wxPoint p(pos.x+sz.x, pos.y+wxPG_BUTTON_SIZEDEC-wxPG_NAT_BUTTON_BORDER_Y); wxSize s(25, -1); wxButton* but = new wxButton(); but->Create(GetPanel(),wxPG_SUBID2,wxT("..."),p,s,wxWANTS_CHARS); // Now that we know the size, move to the correct position p.x = pos.x + sz.x - but->GetSize().x - 2; but->Move(p); #else wxSize s(sz.y-(wxPG_BUTTON_SIZEDEC*2)+(wxPG_NAT_BUTTON_BORDER_Y*2), sz.y-(wxPG_BUTTON_SIZEDEC*2)+(wxPG_NAT_BUTTON_BORDER_Y*2)); // Reduce button width to lineheight if ( s.x > m_lineHeight ) s.x = m_lineHeight; #ifdef __WXGTK__ // On wxGTK, take fixed button margins into account if ( s.x < 25 ) s.x = 25; #endif wxPoint p(pos.x+sz.x-s.x, pos.y+wxPG_BUTTON_SIZEDEC-wxPG_NAT_BUTTON_BORDER_Y); wxButton* but = new wxButton(); #ifdef __WXMSW__ but->Hide(); #endif but->Create(GetPanel(),wxPG_SUBID2,wxT("..."),p,s,wxWANTS_CHARS); #ifdef __WXGTK__ wxFont font = GetFont(); font.SetPointSize(font.GetPointSize()-2); but->SetFont(font); #else but->SetFont(GetFont()); #endif #endif if ( selected->HasFlag(wxPG_PROP_READONLY) ) but->Disable(); return but; } // ----------------------------------------------------------------------- wxWindow* wxPropertyGrid::GenerateEditorTextCtrlAndButton( const wxPoint& pos, const wxSize& sz, wxWindow** psecondary, int limitedEditing, wxPGProperty* property ) { wxButton* but = (wxButton*)GenerateEditorButton(pos,sz); *psecondary = (wxWindow*)but; if ( limitedEditing ) { #ifdef __WXMSW__ // There is button Show in GenerateEditorTextCtrl as well but->Show(); #endif return (wxWindow*) NULL; } wxString text; if ( !property->IsValueUnspecified() ) text = property->GetValueString(property->HasFlag(wxPG_PROP_READONLY)?0:wxPG_EDITABLE_VALUE); return GenerateEditorTextCtrl(pos,sz,text,but,property->m_maxLen); } // ----------------------------------------------------------------------- void wxPropertyGrid::SetEditorAppearance( const wxPGCell& cell ) { wxWindow* editor = GetEditorControl(); if ( !editor ) return; // Get old editor appearance const wxPGCell& oCell = m_editorAppearance; wxPGProperty* property = GetSelection(); wxTextCtrl* tc = GetEditorTextCtrl(); wxPGComboBox* cb; if ( editor->IsKindOf(CLASSINFO(wxPGOwnerDrawnComboBox)) ) cb = (wxPGComboBox*) editor; else cb = NULL; if ( tc || cb ) { wxString tcText; bool changeText = false; if ( cell.HasText() && !IsEditorFocused() ) { tcText = cell.GetText(); changeText = true; } else if ( oCell.HasText() ) { tcText = GetSelection()->GetValueString( property->HasFlag(wxPG_PROP_READONLY)?0:wxPG_EDITABLE_VALUE); changeText = true; } if ( changeText ) { if ( tc ) { // The next line prevents spurious EVT_TEXT from being // received. SetupTextCtrlValue(tcText); tc->SetValue(tcText); } else { cb->SetText(tcText); } } } // We used to obtain wxVisualAttributes via // editor->GetDefaultAttributes() here, but that is not // very consistently implemented in wx2.8, so it is safer // to just use colours from wxSystemSettings etc. const wxColour& fgCol = cell.GetFgCol(); if ( wxGDI_IS_OK(fgCol) ) { editor->SetForegroundColour(fgCol); // Set for wxTextCtrl separately to work around bug in wx2.8 // that may not be fixable due to ABI compatibility issues. if ( tc && tc != editor ) tc->SetForegroundColour(fgCol); } else if ( wxGDI_IS_OK(oCell.GetFgCol()) ) { wxColour vColFg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT); editor->SetForegroundColour(vColFg); if ( tc && tc != editor ) tc->SetForegroundColour(vColFg); } const wxColour& bgCol = cell.GetBgCol(); if ( wxGDI_IS_OK(bgCol) ) { editor->SetBackgroundColour(bgCol); if ( tc && tc != editor ) tc->SetBackgroundColour(bgCol); } else if ( wxGDI_IS_OK(oCell.GetBgCol()) ) { wxColour vColBg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW); editor->SetBackgroundColour(vColBg); if ( tc && tc != editor ) tc->SetBackgroundColour(vColBg); } const wxFont& font = cell.GetFont(); if ( wxGDI_IS_OK(font) ) { editor->SetFont(font); if ( tc && tc != editor ) tc->SetFont(font); } else if ( wxGDI_IS_OK(oCell.GetFont()) ) { wxFont vFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); editor->SetFont(vFont); if ( tc && tc != editor ) tc->SetFont(vFont); } m_editorAppearance.Assign(cell); } // ----------------------------------------------------------------------- wxTextCtrl* wxPropertyGrid::GetEditorTextCtrl() const { wxWindow* wnd = GetEditorControl(); if ( !wnd ) return NULL; if ( wnd->IsKindOf(CLASSINFO(wxTextCtrl)) ) return wxStaticCast(wnd, wxTextCtrl); if ( wnd->IsKindOf(CLASSINFO(wxPGOwnerDrawnComboBox)) ) { wxPGOwnerDrawnComboBox* cb = wxStaticCast(wnd, wxPGOwnerDrawnComboBox); return cb->GetTextCtrl(); } return NULL; } // ----------------------------------------------------------------------- #if defined(__WXMSW__) && !defined(__WXWINCE__) bool wxPG_TextCtrl_SetMargins(wxWindow* tc, const wxPoint& margins) { ::SendMessage(GetHwndOf(tc), EM_SETMARGINS, EC_LEFTMARGIN | EC_RIGHTMARGIN, MAKELONG(margins.x, margins.x)); return true; } /*#elif defined(__WXGTK20__) // // NOTE: For this to work we need to somehow include gtk devel // in the bake/makefile. // #include <gtk/gtk.h> bool wxPG_TextCtrl_SetMargins(wxWindow* tc, const wxPoint& margins) { // // NB: This code has been ported from wx2.9 SVN trunk // #if GTK_CHECK_VERSION(2,10,0) GtkEntry *entry = NULL; entry = GTK_ENTRY( m_widget ); if ( !entry ) return false; const GtkBorder* oldBorder = gtk_entry_get_inner_border(entry); GtkBorder* newBorder; if ( oldBorder ) { newBorder = gtk_border_copy(oldBorder); } else { #if GTK_CHECK_VERSION(2,14,0) newBorder = gtk_border_new(); #else newBorder = g_slice_new0(GtkBorder); #endif // Use some reasonable defaults for initial margins newBorder->left = 2; newBorder->right = 2; // These numbers seem to let the text remain vertically centered // in common use scenarios when margins.y == -1. newBorder->top = 3; newBorder->bottom = 3; } if ( margins.x != -1 ) newBorder->left = (gint) margins.x; if ( margins.y != -1 ) newBorder->top = (gint) margins.y; gtk_entry_set_inner_border(entry, newBorder); #if GTK_CHECK_VERSION(2,14,0) gtk_border_free(newBorder); #else g_slice_free(GtkBorder, newBorder); #endif return true; #else wxUnusedVar(tc); wxUnusedVar(margins); return false; #endif } */ #else bool wxPG_TextCtrl_SetMargins(wxWindow* tc, const wxPoint& margins) { wxUnusedVar(tc); wxUnusedVar(margins); return false; } #endif // ----------------------------------------------------------------------- // wxPGEditorDialogAdapter // ----------------------------------------------------------------------- IMPLEMENT_ABSTRACT_CLASS(wxPGEditorDialogAdapter, wxObject) bool wxPGEditorDialogAdapter::ShowDialog( wxPropertyGrid* propGrid, wxPGProperty* property ) { if ( !propGrid->EditorValidate() ) return false; bool res = DoShowDialog( propGrid, property ); if ( res ) { propGrid->ValueChangeInEvent( m_value ); return true; } return false; } // ----------------------------------------------------------------------- // wxPGMultiButton // ----------------------------------------------------------------------- wxPGMultiButton::wxPGMultiButton( wxPropertyGrid* pg, const wxSize& sz ) : wxWindow( pg->GetPanel(), wxPG_SUBID2, wxPoint(-100,-100), wxSize(0, sz.y) ), m_fullEditorSize(sz), m_buttonsWidth(0) { SetBackgroundColour(pg->GetCellBackgroundColour()); } int wxPGMultiButton::GenId( int id ) const { if ( id < -1 ) { if ( m_buttons.size() ) id = GetButton(m_buttons.size()-1)->GetId() + 1; else id = wxPG_SUBID2; } return id; } #if wxUSE_BMPBUTTON void wxPGMultiButton::Add( const wxBitmap& bitmap, int id ) { id = GenId(id); wxSize sz = GetSize(); wxButton* button = new wxBitmapButton( this, id, bitmap, wxPoint(sz.x, 0), wxSize(sz.y, sz.y) ); m_buttons.push_back(button); int bw = button->GetSize().x; SetSize(wxSize(sz.x+bw,sz.y)); m_buttonsWidth += bw; } #endif void wxPGMultiButton::Add( const wxString& label, int id ) { id = GenId(id); wxSize sz = GetSize(); wxButton* button = new wxButton( this, id, label, wxPoint(sz.x, 0), wxSize(sz.y, sz.y) ); m_buttons.push_back(button); int bw = button->GetSize().x; SetSize(wxSize(sz.x+bw,sz.y)); m_buttonsWidth += bw; } // -----------------------------------------------------------------------
[ [ [ 1, 678 ], [ 685, 986 ], [ 988, 988 ], [ 996, 1380 ], [ 1387, 1462 ], [ 1469, 1516 ], [ 1523, 1544 ], [ 1551, 1914 ], [ 1921, 2598 ] ], [ [ 679, 684 ], [ 987, 987 ], [ 989, 995 ], [ 1381, 1386 ], [ 1463, 1468 ], [ 1517, 1522 ], [ 1545, 1550 ], [ 1915, 1920 ] ] ]
cbee08120017b851ad6d655a24adb041ff5fcac5
ec4c161b2baf919424d8d21cd0780cf8065e3f69
/Velo/Source/Embedded Controller/arduino/cProcesses.h
75fe7df619e6f228d28bf1976640a5246f68ac24
[]
no_license
jhays200/EV-Tracking
b215d2a915987fe7113a05599bda53f254248cfa
06674e6f0f04fc2d0be1b1d37124a9a8e0144467
refs/heads/master
2016-09-05T18:41:21.650852
2011-06-04T01:50:25
2011-06-04T01:50:25
1,673,213
2
0
null
null
null
null
UTF-8
C++
false
false
3,791
h
/////////////////////////////////////////////////////////// // cProcesses.h // Implementation of the Class cProcesses // Created on: 02-May-2010 5:18:31 PM // Original author: Shawn /////////////////////////////////////////////////////////// #if !defined(EA_DAA1CE03_7A71_4360_871D_A6883563C1CF__INCLUDED_) #define EA_DAA1CE03_7A71_4360_871D_A6883563C1CF__INCLUDED_ #include "cContext.h" #include "cList.h" class cProcesses { public: cProcesses(); ~cProcesses(); unsigned int Spawn(void (*function)(), unsigned int priority); void Kill(); void Yield(unsigned int milliseconds = 0); void Scheduler(); void EnableInterrupts(bool force = false); void DisableInterrupts(void); cContext* CurrentProcess; cList Threads; cList Schedule; unsigned int PIDCount; unsigned int InterruptFlag; }; #define STACKSIZE 0x200 /// <summary> /// Cause Software Interrupt using the Timer 0 Overflow. /// </summary> //TODO: Set Timer Overflow TIFR0.TOV0 #define CauseThreadSwitch() asm volatile ("nop"); /// <summary> /// Save Thread Context /// </summary> #define SaveContext() \ asm volatile ( "push r0 \n\t" \ "in r0, __SREG__ \n\t" \ "cli \n\t" \ "push r0 \n\t" \ "push r1 \n\t" \ "clr r1 \n\t" \ "push r2 \n\t" \ "push r3 \n\t" \ "push r4 \n\t" \ "push r5 \n\t" \ "push r6 \n\t" \ "push r7 \n\t" \ "push r8 \n\t" \ "push r9 \n\t" \ "push r10 \n\t" \ "push r11 \n\t" \ "push r12 \n\t" \ "push r13 \n\t" \ "push r14 \n\t" \ "push r15 \n\t" \ "push r16 \n\t" \ "push r17 \n\t" \ "push r18 \n\t" \ "push r19 \n\t" \ "push r20 \n\t" \ "push r21 \n\t" \ "push r22 \n\t" \ "push r23 \n\t" \ "push r24 \n\t" \ "push r25 \n\t" \ "push r26 \n\t" \ "push r27 \n\t" \ "push r28 \n\t" \ "push r29 \n\t" \ "push r30 \n\t" \ "push r31 \n\t" \ "lds r26, CurrentThread \n\t" \ "lds r27, CurrentThread + 1 \n\t" \ "in r0, 0x3d \n\t" \ "st x+, r0 \n\t" \ "in r0, 0x3e \n\t" \ "st x+, r0 \n\t" \ ); /// <summary> /// Restore Thread Context /// </summary> #define RestoreContext() \ asm volatile( "lds r26, CurrentThread \n\t" \ "lds r27, CurrentThread + 1 \n\t" \ "ld r28, x+ \n\t" \ "out __SP_L__, r28 \n\t" \ "ld r29, x+ \n\t" \ "out __SP_H__, r29 \n\t" \ "pop r31 \n\t" \ "pop r30 \n\t" \ "pop r29 \n\t" \ "pop r28 \n\t" \ "pop r27 \n\t" \ "pop r26 \n\t" \ "pop r25 \n\t" \ "pop r24 \n\t" \ "pop r23 \n\t" \ "pop r22 \n\t" \ "pop r21 \n\t" \ "pop r20 \n\t" \ "pop r19 \n\t" \ "pop r18 \n\t" \ "pop r17 \n\t" \ "pop r16 \n\t" \ "pop r15 \n\t" \ "pop r14 \n\t" \ "pop r13 \n\t" \ "pop r12 \n\t" \ "pop r11 \n\t" \ "pop r10 \n\t" \ "pop r9 \n\t" \ "pop r8 \n\t" \ "pop r7 \n\t" \ "pop r6 \n\t" \ "pop r5 \n\t" \ "pop r4 \n\t" \ "pop r3 \n\t" \ "pop r2 \n\t" \ "pop r1 \n\t" \ "pop r0 \n\t" \ "out __SREG__, r0 \n\t" \ "pop r0 \n\t" \ ); #endif // !defined(EA_DAA1CE03_7A71_4360_871D_A6883563C1CF__INCLUDED_)
[ [ [ 1, 139 ] ] ]
0d39be9d1eb928aaf96b9d623eda8d75cfac3136
83c9b35f2327528b6805b8e9de147ead75e8e351
/renderers/VideoRenderer.cpp
7e45ca9b99098b8b26bc6ef81f10280a548bf30d
[]
no_license
playmodes/playmodes
ec6ced2e637769353eb66db89aa88ebd1d5185ac
9a91b192be92c8dedc67cbd126d5a50a4d2b9c54
refs/heads/master
2021-01-22T10:14:18.586477
2010-01-02T17:55:50
2010-01-02T17:55:50
456,188
1
0
null
null
null
null
UTF-8
C++
false
false
2,377
cpp
/* * VideoRenderer.cpp * * Created on: 09-oct-2008 * Author: arturo castro */ #include "VideoRenderer.h" ofEventArgs videoRendererVoidArgs; VideoRenderer::VideoRenderer(VideoSource * source) { this->source=source; //texAllocated=false; scale = 1; rotationZ = 0; rotationX = 0; rotationY = 0; x = 0; y = 0; z = 0; anchorX = CAPTURE_WIDTH/2; anchorY = CAPTURE_HEIGHT/2; tintR=255; tintG=255; tintB=255; alpha=255; minmaxBlend=false; activateShader=false; isDrawing=true; //shader.loadShader(""); } VideoRenderer::~VideoRenderer() { } void VideoRenderer::draw(){ if(isDrawing){ if(activateShader) shader.setShaderActive(true); if(alpha<255){ ofEnableAlphaBlending(); if(minmaxBlend){ glBlendEquationEXT(GL_MAX); //glBlendFuncSeparateEXT( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA, GL_DST_ALPHA ); //glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); //glBlendEquationSeparateEXT(GL_MAX,GL_ADD); }else{ glBlendEquationEXT(GL_MIN); //glBlendFuncSeparateEXT( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA, GL_DST_ALPHA ); //glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); //glBlendEquationSeparateEXT(GL_MIN,GL_ADD); } ofSetColor(tintR,tintG,tintB,alpha); /// drawing the video render drawNextFrame(); ofDisableAlphaBlending(); glBlendEquationEXT(GL_FUNC_ADD); }else{ ofSetColor(tintR,tintG,tintB); drawNextFrame(); } if(activateShader) shader.setShaderActive(false); } } void VideoRenderer::drawNextFrame(){ VideoFrame * frame = source->getNextVideoFrame(); if(frame!=NULL){ if(!frame->isTexAllocated()) frame->update(videoRendererVoidArgs); glPushMatrix(); glTranslatef(x,y,z); glTranslatef((anchorX*scale+x),(anchorY*scale+y),0); glRotatef(rotationZ,0,0,1); glRotatef(rotationX,1,0,0); glRotatef(rotationY,0,1,0); glTranslatef(-(anchorX*scale+x),-(anchorY*scale+y),0); frame->getTexture()->draw(0,0,frame->w*scale,frame->h*scale); glPopMatrix(); frame->release(); } }
[ [ [ 1, 90 ] ] ]
d30efa0d70771693f997123780b8e4aa5a92b00a
41efaed82e413e06f31b65633ed12adce4b7abc2
/cglib/src/cg/IReshapeEventListener.h
e8bcb0059dfbf822e2731282f913a0dc6aa3f0d4
[]
no_license
ivandro/AVT---project
e0494f2e505f76494feb0272d1f41f5d8f117ac5
ef6fe6ebfe4d01e4eef704fb9f6a919c9cddd97f
refs/heads/master
2016-09-06T03:45:35.997569
2011-10-27T15:00:14
2011-10-27T15:00:14
2,642,435
0
2
null
2016-04-08T14:24:40
2011-10-25T09:47:13
C
UTF-8
C++
false
false
1,491
h
// This file is part of CGLib. // // CGLib 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. // // CGLib 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 CGLib; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // Copyright 2007 Carlos Martinho #ifndef IRESHAPE_EVENT_LISTENER_H #define IRESHAPE_EVENT_LISTENER_H namespace cg { /** cg::IReshapeEventListener is the callback interface for reshape events. */ class IReshapeEventListener { public: /** When a window is reshaped, a reshape event is generated in GLUT and distributed by * cglib to all registred Entities that implement the IReshapeEventListener interface. * For more details, please refer to glutReshapeFunc in GLUT documentation. * \param width The new window's width in pixels. * \param height The new window's height in pixels. */ virtual void onReshape(int width, int height) = 0; }; } #endif // IRESHAPE_EVENT_LISTENER_H
[ "Moreira@Moreira-PC.(none)" ]
[ [ [ 1, 39 ] ] ]
d82f5e2c8b36893166e771c9cc44c2ff2b9de486
e53e3f6fac0340ae0435c8e60d15d763704ef7ec
/WDL/resample.h
44907d2d14bf577e1277e177c9f2e6237867cc32
[]
no_license
b-vesco/vfx-wdl
906a69f647938b60387d8966f232a03ce5b87e5f
ee644f752e2174be2fefe43275aec2979f0baaec
refs/heads/master
2020-05-30T21:37:06.356326
2011-01-04T08:54:45
2011-01-04T08:54:45
848,136
2
0
null
null
null
null
UTF-8
C++
false
false
3,342
h
/* ** Copyright (C) 2010 Cockos Incorporated ** LGPL **/ #ifndef _WDL_RESAMPLE_H_ #define _WDL_RESAMPLE_H_ #include "wdltypes.h" #include "heapbuf.h" // default to floats for sinc filter ceofficients #ifdef WDL_RESAMPLE_FULL_SINC_PRECISION typedef double WDL_SincFilterSample; #else typedef float WDL_SincFilterSample; #endif // default to doubles for audio samples #ifdef WDL_RESAMPLE_TYPE typedef WDL_RESAMPLE_TYPE WDL_ResampleSample; #else typedef double WDL_ResampleSample; #endif #ifndef WDL_RESAMPLE_MAX_FILTERS #define WDL_RESAMPLE_MAX_FILTERS 4 #endif #ifndef WDL_RESAMPLE_MAX_NCH #define WDL_RESAMPLE_MAX_NCH 64 #endif class WDL_Resampler { public: WDL_Resampler(); ~WDL_Resampler(); // if sinc set, it overrides interp or filtercnt void SetMode(bool interp, int filtercnt, bool sinc, int sinc_size=64, int sinc_interpsize=32); void SetFilterParms(float filterpos=0.693, float filterq=0.707) { m_filterpos=filterpos; m_filterq=filterq; } // used for filtercnt>0 but not sinc void SetFeedMode(bool wantInputDriven) { m_feedmode=wantInputDriven; } // if true, that means the first parameter to ResamplePrepare will specify however much input you have, not how much you want void Reset(double fracpos=0.0); void SetRates(double rate_in, double rate_out); double GetCurrentLatency(); // amount of input that has been received but not yet converted to output, in seconds // req_samples is output samples desired if !wantInputDriven, or if wantInputDriven is input samples that we have // returns number of samples desired (put these into *inbuffer) // note that it is safe to call ResamplePrepare without calling ResampleOut (the next call of ResamplePrepare will function as normal) int ResamplePrepare(int req_samples, int nch, WDL_ResampleSample **inbuffer); // if numsamples_in < the value return by ResamplePrepare(), then it will be flushed to produce all remaining valid samples // do NOT call with nsamples_in greater than the value returned from resamplerprpare()! the extra samples will be ignored. // returns number of samples successfully outputted to out int ResampleOut(WDL_ResampleSample *out, int nsamples_in, int nsamples_out, int nch); private: void BuildLowPass(double filtpos); void inline SincSample(WDL_ResampleSample *outptr, WDL_ResampleSample *inptr, double fracpos, int nch, WDL_SincFilterSample *filter, int filtsz); void inline SincSample1(WDL_ResampleSample *outptr, WDL_ResampleSample *inptr, double fracpos, WDL_SincFilterSample *filter, int filtsz); void inline SincSample2(WDL_ResampleSample *outptr, WDL_ResampleSample *inptr, double fracpos, WDL_SincFilterSample *filter, int filtsz); double m_sratein WDL_FIXALIGN; double m_srateout; double m_fracpos; double m_ratio; double m_filter_ratio; float m_filterq, m_filterpos; WDL_TypedBuf<WDL_ResampleSample> m_rsinbuf; WDL_TypedBuf<WDL_SincFilterSample> m_filter_coeffs; class WDL_Resampler_IIRFilter; WDL_Resampler_IIRFilter *m_iirfilter; int m_filter_coeffs_size; int m_last_requested; int m_filtlatency; int m_samples_in_rsinbuf; int m_lp_oversize; int m_sincsize; int m_filtercnt; int m_sincoversize; bool m_interp; bool m_feedmode; }; #endif
[ [ [ 1, 46 ], [ 48, 99 ] ], [ [ 47, 47 ] ] ]
4d546ca1347f6b099928eff9d25d21df1c7dc1a5
0454def9ffc8db9884871a7bccbd7baa4322343b
/src/plugins/audiotag/QUAudioTagTaskFactory.h
a6425530e9f33ff5bf6964de872df94fb0879e83
[]
no_license
escaped/uman
e0187d1d78e2bb07dade7ef6ef041b6ed424a2d3
bedc1c6c4fc464be4669f03abc9bac93e7e442b0
refs/heads/master
2016-09-05T19:26:36.679240
2010-07-26T07:55:31
2010-07-26T07:55:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
799
h
#ifndef AUDIOTAGTASKFACTORY_H_ #define AUDIOTAGTASKFACTORY_H_ #include <QObject> #include <QDomDocument> #include "QUScriptableTaskFactory.h" class QUAudioTagTaskFactory: public QUScriptableTaskFactory { Q_OBJECT public: QUAudioTagTaskFactory(QObject *parent = 0); virtual QString version() const { return "1.0.0"; } virtual QString name() const; virtual QString productName() const; virtual QString description() const; virtual QString author() const { return "Marcel Taeumel"; } public slots: virtual int addConfiguration(QWidget *parent = 0); protected: virtual QDir configurationDirectory(); virtual QUTask* createTask(QDomDocument *configuration); virtual QMap<QString, QString> translationLocations() const; }; #endif // AUDIOTAGTASKFACTORY_H_
[ [ [ 1, 30 ] ] ]
518cdaaf2b955b2655d51bd55ac0b7bf186d8477
8ddac2310fb59dfbfb9b19963e3e2f54e063c1a8
/Logiciel_PC/WishBoneMonitor/registerlistview.cpp
742c21e7472569d9cd27f6a886199bc3ca3403da
[]
no_license
Julien1138/WishBoneMonitor
75efb53585acf4fd63e75fb1ea967004e6caa870
3062132ecd32cd0ffdd89e8a56711ae9a93a3c48
refs/heads/master
2021-01-12T08:25:34.115470
2011-05-02T16:35:54
2011-05-02T16:35:54
76,573,671
0
0
null
null
null
null
ISO-8859-1
C++
false
false
12,067
cpp
#include "registerlistview.h" #include "addregisterdialog.h" #include "wishboneregister.h" #include <QContextMenuEvent> #include <QMenu> #include <QRect> #include <QMessageBox> #include <QLineEdit> #include <QComboBox> #include <QSignalMapper> RegisterListView::RegisterListView(WishBoneMonitor* pDoc, QWidget *parent) : QWidget(parent), m_pDoc(pDoc) { m_Table.setColumnCount(11); QStringList HLabels; HLabels << "Adresse" << "Nom" << "Valeur Hex" << "Echelle" << "Unité" << "Signe" << "Valeur Min" << "Valeur Max" << "Direction" << "Periode (ms)" << ""; m_Table.setHorizontalHeaderLabels(HLabels); m_Table.setColumnWidth( 0, 50); // Adresse m_Table.setColumnWidth( 1, 150); // Nom m_Table.setColumnWidth( 2, 80); // Valeur Hex m_Table.setColumnWidth( 3, 50); // Echelle m_Table.setColumnWidth( 4, 50); // Unité m_Table.setColumnWidth( 5, 80); // Signe m_Table.setColumnWidth( 6, 80); // Valeur Min m_Table.setColumnWidth( 7, 80); // Valeur Max m_Table.setColumnWidth( 8, 70); // Direction m_Table.setColumnWidth( 9, 80); // Periode m_Table.setColumnWidth(10, 70); // Supprimer m_Layout.addWidget(&m_Table, 0, 0); setLayout(&m_Layout); connect(&m_Table, SIGNAL(cellChanged(int,int)), this , SLOT(ModifyRegister(int, int))); UpdateDisplay(); } void RegisterListView::UpdateDisplay() { m_UpdateInProgress = true; m_Table.setRowCount(m_pDoc->GetRegisterList()->count()); QSignalMapper *mapper = new QSignalMapper(); QSignalMapper *UpdateValueMapper = new QSignalMapper(); for (int i(0) ; i < m_pDoc->GetRegisterList()->count() ; i++) { int k(0); // Adresse m_Table.setItem(i, k, new QTableWidgetItem("0x" + QString::number(m_pDoc->GetRegisterList()->value(i)->Address(), 16))); m_Table.item(i, k)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); if (!(m_pDoc->ConfigMode())) { m_Table.item(i, k)->setFlags(m_Table.item(i, k)->flags() & ~Qt::ItemIsEnabled); } k++; // Nom m_Table.setItem(i, k, new QTableWidgetItem(m_pDoc->GetRegisterList()->value(i)->Name())); if (!(m_pDoc->ConfigMode())) { m_Table.item(i, k)->setFlags(m_Table.item(i, k)->flags() & ~Qt::ItemIsEnabled); } k++; // Valeur Hex m_Table.setItem(i, k, new QTableWidgetItem("0x" + QString::number(m_pDoc->GetRegisterList()->value(i)->ValueHex(), 16))); m_Table.item(i, k)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); m_Table.item(i, k)->setFlags(m_Table.item(i, k)->flags() & ~Qt::ItemIsEnabled); connect(m_pDoc->GetRegisterList()->value(i), SIGNAL(UpdateWidget()), UpdateValueMapper, SLOT(map())); UpdateValueMapper->setMapping(m_pDoc->GetRegisterList()->value(i), i); k++; // Coefficient d'échelle m_Table.setItem(i, k, new QTableWidgetItem(QString::number((double) m_pDoc->GetRegisterList()->value(i)->ScaleCoefficient()))); m_Table.item(i, k)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); if (!(m_pDoc->ConfigMode())) { m_Table.item(i, k)->setFlags(m_Table.item(i, k)->flags() & ~Qt::ItemIsEnabled); } k++; // Unité m_Table.setItem(i, k, new QTableWidgetItem(m_pDoc->GetRegisterList()->value(i)->Unit())); if (!(m_pDoc->ConfigMode())) { m_Table.item(i, k)->setFlags(m_Table.item(i, k)->flags() & ~Qt::ItemIsEnabled); } k++; // Signe QComboBox* pComboSigne = new QComboBox; pComboSigne->addItem("Signé"); pComboSigne->addItem("Non Signé"); m_Table.setCellWidget(i, k, pComboSigne); pComboSigne->setCurrentIndex(m_pDoc->GetRegisterList()->value(i)->Signed() ? 0 : 1); pComboSigne->setEnabled(m_pDoc->ConfigMode()); connect(pComboSigne, SIGNAL(currentIndexChanged(int)), mapper, SLOT(map())); mapper->setMapping(pComboSigne, i); connect(pComboSigne, SIGNAL(currentIndexChanged(int)), this, SLOT(ModifySignBox(int))); k++; // Valeur Min if (m_pDoc->GetRegisterList()->value(i)->Signed()) { m_Table.setItem(i, k, new QTableWidgetItem(QString::number((signed long) (m_pDoc->GetRegisterList()->value(i)->ValueMin())))); } else { m_Table.setItem(i, k, new QTableWidgetItem(QString::number((unsigned long) (m_pDoc->GetRegisterList()->value(i)->ValueMin())))); } if (!m_pDoc->GetRegisterList()->value(i)->Write_nRead()) { m_Table.item(i, k)->setFlags(m_Table.item(i, k)->flags() & ~Qt::ItemIsEnabled); } if (!(m_pDoc->ConfigMode())) { m_Table.item(i, k)->setFlags(m_Table.item(i, k)->flags() & ~Qt::ItemIsEnabled); } m_Table.item(i, k)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); k++; // Valeur Max if (m_pDoc->GetRegisterList()->value(i)->Signed()) { m_Table.setItem(i, k, new QTableWidgetItem(QString::number((signed long) (m_pDoc->GetRegisterList()->value(i)->ValueMax())))); } else { m_Table.setItem(i, k, new QTableWidgetItem(QString::number((unsigned long) (m_pDoc->GetRegisterList()->value(i)->ValueMax())))); } if (!m_pDoc->GetRegisterList()->value(i)->Write_nRead()) { m_Table.item(i, k)->setFlags(m_Table.item(i, k)->flags() & ~Qt::ItemIsEnabled); } if (!(m_pDoc->ConfigMode())) { m_Table.item(i, k)->setFlags(m_Table.item(i, k)->flags() & ~Qt::ItemIsEnabled); } m_Table.item(i, k)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); k++; // Direction QComboBox* pComboDir = new QComboBox; pComboDir->addItem("Lecture"); pComboDir->addItem("Ecriture"); m_Table.setCellWidget(i, k, pComboDir); pComboDir->setCurrentIndex(m_pDoc->GetRegisterList()->value(i)->Write_nRead() ? 1 : 0); pComboDir->setEnabled(m_pDoc->ConfigMode()); connect(pComboDir, SIGNAL(currentIndexChanged(int)), mapper, SLOT(map())); mapper->setMapping(pComboDir, i); connect(pComboDir, SIGNAL(currentIndexChanged(int)), this, SLOT(ModifyDirectionBox(int))); k++; // Periode m_Table.setItem(i, k, new QTableWidgetItem(QString::number(m_pDoc->GetRegisterList()->value(i)->Period()))); if (m_pDoc->GetRegisterList()->value(i)->Write_nRead()) { m_pDoc->GetRegisterList()->value(i)->SetPeriod(0); m_Table.item(i, k)->setFlags(m_Table.item(i, k)->flags() & ~Qt::ItemIsEnabled); m_Table.item(i, k)->setText(QString::number(m_pDoc->GetRegisterList()->value(i)->Period())); } if (!(m_pDoc->ConfigMode())) { m_Table.item(i, k)->setFlags(m_Table.item(i, k)->flags() & ~Qt::ItemIsEnabled); } m_Table.item(i, k)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); k++; // Bouton supprimer QPushButton* pDelButton = new QPushButton("Supprimer"); m_Table.setCellWidget(i, k, pDelButton); connect(pDelButton, SIGNAL(pressed()), mapper, SLOT(map())); mapper->setMapping(pDelButton, i); connect(pDelButton, SIGNAL(clicked()), this, SLOT(DelReg())); k++; } connect(mapper, SIGNAL(mapped(int)), &m_Table, SLOT(selectRow(int))); connect(UpdateValueMapper, SIGNAL(mapped(int)), this, SLOT(UpdateRegisterValue(int))); m_UpdateInProgress = false; } void RegisterListView::AddReg() { AddRegisterDialog Dlg(true, this); Dlg.setModal(true); if (Dlg.exec() == QDialog::Accepted) { WishBoneRegister Reg(Dlg.Name(), Dlg.Address(), Dlg.ValueMin(), Dlg.ValueMax(), Dlg.Signed(), Dlg.ScaleCoefficient(), Dlg.Unit(), Dlg.Write_nRead(), Dlg.Periode()); if (!m_pDoc->AddRegister(Reg)) { QMessageBox::warning(this, "Ajout d'un registre", "Attention, ce registre existe déjà !"); } UpdateDisplay(); } } void RegisterListView::DelReg() { m_pDoc->DelRegister(m_Table.currentRow()); UpdateDisplay(); } void RegisterListView::contextMenuEvent(QContextMenuEvent * event) { if (m_pDoc->ConfigMode()) { if (event->x() > m_Table.x() && event->x() < (m_Table.x() + m_Table.width()) && event->y() > m_Table.y() && event->y() < (m_Table.y() + m_Table.height())) { QMenu * menu = new QMenu(this); menu->addAction("Ajouter un registre", this, SLOT(AddReg())); menu->exec(event->globalPos()); } } } void RegisterListView::ModifyRegister(int currentRow, int currentColumn) { if (!m_UpdateInProgress) { if (currentColumn == 0) { if (m_pDoc->RegisterExists(m_Table.item(currentRow, currentColumn)->text().toULong(0,0), m_pDoc->GetRegisterList()->value(currentRow)->Write_nRead())) { QMessageBox::warning(this, "Ajout d'un registre", "Attention, ce registre existe déjà !"); m_Table.setCurrentCell(currentRow, currentColumn); } else { m_pDoc->GetRegisterList()->value(currentRow)->SetAddress(m_Table.item(currentRow, currentColumn)->text().toULong(0,0)); } } else if (currentColumn == 1) { m_pDoc->GetRegisterList()->value(currentRow)->SetName(m_Table.item(currentRow, currentColumn)->text()); } else if (currentColumn == 3) { m_pDoc->GetRegisterList()->value(currentRow)->SetScaleCoefficient(m_Table.item(currentRow, currentColumn)->text().toDouble()); } else if (currentColumn == 4) { m_pDoc->GetRegisterList()->value(currentRow)->SetUnit(m_Table.item(currentRow, currentColumn)->text()); } else if (currentColumn == 6) { m_pDoc->GetRegisterList()->value(currentRow)->SetValueMin(m_Table.item(currentRow, currentColumn)->text().toLong(0,0)); } else if (currentColumn == 7) { m_pDoc->GetRegisterList()->value(currentRow)->SetValueMax(m_Table.item(currentRow, currentColumn)->text().toLong(0,0)); } else if (currentColumn == 9) { m_pDoc->GetRegisterList()->value(currentRow)->SetPeriod(m_Table.item(currentRow, currentColumn)->text().toLong(0,0)); } UpdateDisplay(); } } void RegisterListView::ModifySignBox(int Idx) { m_pDoc->GetRegisterList()->value(m_Table.currentRow())->SetSigned(Idx == 0 ? true : false); UpdateDisplay(); } void RegisterListView::ModifyDirectionBox(int Idx) { if (m_pDoc->RegisterExists(m_pDoc->GetRegisterList()->value(m_Table.currentRow())->Address(), Idx == 0 ? false : true)) { QMessageBox::warning(this, "Ajout d'un registre", "Attention, ce registre existe déjà !"); } else { m_pDoc->GetRegisterList()->value(m_Table.currentRow())->SetWrite_nRead(Idx == 0 ? false : true); } UpdateDisplay(); } void RegisterListView::UpdateRegisterValue(int Idx) { if (m_UpdateInProgress == false) { m_Table.item(Idx, 2)->setText("0x" + QString::number(m_pDoc->GetRegisterList()->value(Idx)->ValueHex(), 16)); } }
[ [ [ 1, 308 ] ] ]
0e086690372886383ec58e96a9b8113abe682a92
e5f7a02c92c5a60c924e07813bc0b7b8944c2ce8
/8-event_serialization/8.5/Coroutine.h
0eb0dd5087066e8b5e9f993dace65d51990b7599
[]
no_license
7shi/thunkben
b8fe8f29b43c030721e8a08290c91275c9f455fe
9bc99c5a957e087bb41bd6f87cf7dfa44e7b55f6
refs/heads/main
2022-12-27T19:53:39.322464
2011-11-30T16:57:45
2011-11-30T16:57:45
303,163,701
0
0
null
null
null
null
UTF-8
C++
false
false
2,167
h
#pragma once #include <vector> #include <functional> #include <stack> typedef struct { unsigned long eip, esp, ebp, ebx, edi, esi; void *stack; int length; } myjmp_buf; extern int _fastcall mysetjmp(myjmp_buf *jbuf); extern void _fastcall mylongjmp(myjmp_buf *jbuf, int value); extern void save_stack(std::vector<char> *dest, unsigned long last, myjmp_buf *callee); class CoroutineBase { public: virtual ~CoroutineBase(); }; extern std::stack<CoroutineBase *> coroutines; template <class T> class Coroutine : public CoroutineBase { myjmp_buf caller, callee; std::vector<char> stack; std::function<void()> f; int status; unsigned long last; void exec() { f(); mylongjmp(&caller, 2); } public: T value; Coroutine() : status(0) {} Coroutine(const decltype(f) &f) : f(f), status(0) {} void operator=(const decltype(f) &f) { this->f = f; } void reset() { if (status == 3) status = 0; } bool operator()() { if (status == 0) _alloca(32 * 1024); switch (mysetjmp(&caller)) { case 1: return true; case 2: coroutines.pop(); status = 3; return false; } switch (status) { case 0: last = caller.esp; status = 1; coroutines.push(this); exec(); case 2: if (caller.esp < callee.esp) return false; status = 1; coroutines.push(this); mylongjmp(&callee, 1); } return false; } T yield(T value) { if (coroutines.top() == this) { coroutines.pop(); status = 2; this->value = value; if (mysetjmp(&callee) == 0) { save_stack(&stack, last, &callee); mylongjmp(&caller, 1); } } return this->value; } }; template <class T> T yield(T value) { auto cr = dynamic_cast<Coroutine<T> *>(coroutines.top()); return cr ? cr->yield(value) : T(); }
[ [ [ 1, 86 ] ] ]
937c51bb3a20ed7ebd158d21921765cc01713bae
3856c39683bdecc34190b30c6ad7d93f50dce728
/LastProject/Source/Chase.cpp
736ebad2af923e6bd55b7032b2f0b5b5816e5291
[]
no_license
yoonhada/nlinelast
7ddcc28f0b60897271e4d869f92368b22a80dd48
5df3b6cec296ce09e35ff0ccd166a6937ddb2157
refs/heads/master
2021-01-20T09:07:11.577111
2011-12-21T22:12:36
2011-12-21T22:12:36
34,231,967
0
0
null
null
null
null
UHC
C++
false
false
2,964
cpp
#include "stdafx.h" #include "Chase.h" #include "Seek.h" #include "Frequency.h" #include "Charactor.h" #include "Monster.h" Chase* Chase::GetInstance() { static Chase Instance; return &Instance; } VOID Chase::Enter( CMonster* a_pMonster ) { // Chase 초기 정보 설정 a_pMonster->Set_ChaseData(); // 이동 애니메이션으로 바꾼다. a_pMonster->ChangeAnimation( CMonster::ANIM_MOVE ); #ifdef _DEBUG ////CDebugConsole::GetInstance()->Messagef( L"Chase : ANIM_MOVE \n" ); #endif } VOID Chase::Execute( CMonster* a_pMonster ) { // 0.5초 마다 발자국 소리 a_pMonster->Set_UpdateSoundTime(); FLOAT fSoundTime = a_pMonster->Get_SoundTime(); if( fSoundTime >= 0.5f ) { a_pMonster->Set_ClearSoundTime(); CSound::GetInstance()->PlayEffect( CSound::EFFECT_CLOWN_MOVE1 + rand() % 3 ); } a_pMonster->Set_UpdateTime(); FLOAT t = a_pMonster->Get_Time(); if( t >= 0.25f ) { a_pMonster->Set_ClearTime(); a_pMonster->Set_ChaseNextData(); // 10% 확률로 삐에로 웃음소리 if( a_pMonster->Get_MonsterNumber() == 2 ) { if( FastRand2() < 0.1f ) { CSound::GetInstance()->PlayEffect( CSound::EFFECT_CLOWN_LAUGH1 ); } } } else { D3DXVECTOR3 vPos( 0.0f, 0.0f, 0.0f ); D3DXVECTOR2 vAngle( 0.0f, 0.0f ); // 처음 이동할 Path인 경우 if( a_pMonster->Get_ChaseTotalPathCnt() == a_pMonster->Get_ChaseNextPath()->remainedNode ) { // 위치 D3DXVECTOR3 p0 = a_pMonster->Get_ChaseCurrentPos(); D3DXVECTOR3 p1 = a_pMonster->GetWorldPos( a_pMonster->Get_ChaseNextPath()->x, a_pMonster->Get_ChaseNextPath()->y ); D3DXVECTOR3 p2 = a_pMonster->GetWorldPos( a_pMonster->Get_ChaseNextPath()->next->x, a_pMonster->Get_ChaseNextPath()->next->y ); D3DXVec3CatmullRom( &vPos, &p0, &p0, &p1, &p2, t / 0.25f ); // 각도 D3DXVECTOR2 vCurrentAngle( 0.0f, a_pMonster->Get_ChaseAngle0() ); D3DXVECTOR2 vNextAngle( 0.0f, a_pMonster->Get_ChaseAngle1() ); D3DXVec2Lerp( &vAngle, &vCurrentAngle, &vNextAngle, t / 0.25f ); } // 처음과 끝이 아닌 중간 Path else { // 위치 D3DXVECTOR3 p0 = a_pMonster->Get_ChasePreviousPos(); D3DXVECTOR3 p1 = a_pMonster->Get_ChaseCurrentPos(); D3DXVECTOR3 p2 = a_pMonster->GetWorldPos( a_pMonster->Get_ChaseNextPath()->x, a_pMonster->Get_ChaseNextPath()->y ); D3DXVECTOR3 p3 = a_pMonster->GetWorldPos( a_pMonster->Get_ChaseNextPath()->next->x, a_pMonster->Get_ChaseNextPath()->next->y ); D3DXVec3CatmullRom( &vPos, &p0, &p1, &p2, &p3, t / 0.25f ); // 각도 D3DXVECTOR2 vCurrentAngle( 0.0f, a_pMonster->Get_ChaseAngle0() ); D3DXVECTOR2 vNextAngle( 0.0f, a_pMonster->Get_ChaseAngle1() ); D3DXVec2Lerp( &vAngle, &vCurrentAngle, &vNextAngle, t / 0.25f ); } a_pMonster->Set_Pos( vPos ); a_pMonster->Set_Angle( D3DXToRadian( vAngle.y ) ); } } VOID Chase::Exit( CMonster* a_pMonster ) { }
[ "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0", "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0", "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0" ]
[ [ [ 1, 20 ], [ 29, 33 ], [ 47, 47 ], [ 60, 62 ], [ 102, 108 ] ], [ [ 21, 26 ], [ 28, 28 ], [ 34, 46 ], [ 48, 59 ], [ 63, 101 ], [ 109, 109 ] ], [ [ 27, 27 ] ] ]
578624d01a408ed74ed53100a8340a69a5e6e320
867f5533667cce30d0743d5bea6b0c083c073386
/jingxian-downloader/DownloadFrame.functional.cpp
b5c74b0ea3ae13e24c07633a655ab787ead6d8ea
[]
no_license
mei-rune/jingxian-project
32804e0fa82f3f9a38f79e9a99c4645b9256e889
47bc7a2cb51fa0d85279f46207f6d7bea57f9e19
refs/heads/master
2022-08-12T18:43:37.139637
2009-12-11T09:30:04
2009-12-11T09:30:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,900
cpp
/*************************************************************** * Name: jinxian_downloaderMain.cpp * Purpose: Code for Application Frame * Author: runner.mei ([email protected]) * Created: 2008-10-31 * Copyright: runner.mei () * License: **************************************************************/ #include "pre_config.h" #include "DownloadFrame.h" #include "icons/toolbar_invalid.xpm" #include "icons/toolbar_enable.xpm" #include "NewDownload.h" //private: // // wxBitmap m_bitmap_browse_folder[2]; // wxBitmap m_bitmap_delete_download[2]; // wxBitmap m_bitmap_download_properties[2]; // wxBitmap m_bitmap_find[2]; // wxBitmap m_bitmap_find_next[2]; // wxBitmap m_bitmap_move_down[2]; // wxBitmap m_bitmap_move_up[2]; // wxBitmap m_bitmap_new_download[2]; // wxBitmap m_bitmap_open_download_file[2]; // wxBitmap m_bitmap_options[2]; // wxBitmap m_bitmap_pause_download[2]; // wxBitmap m_bitmap_start_download[2]; // void initBitmap(const wxBitmap& xpm, int index ); // void initialize(); void DownloadFrame::initialize() { wxBitmap invalid_bitmap( toolbar_invalid ); wxBitmap enable_bitmap( toolbar_enable ); initBitmap( invalid_bitmap, 0 ); initBitmap( enable_bitmap, 1 ); } void DownloadFrame::initBitmap(const wxBitmap& xpm, int index ) { m_bitmap_browse_folder[index] = xpm.GetSubBitmap( wxRect(5 *24, 0, 24,24 ) ); m_bitmap_delete_download[index] = xpm.GetSubBitmap( wxRect(3 *24, 0, 24,24 ) ); m_bitmap_download_properties[index] = xpm.GetSubBitmap( wxRect(6 *24, 0, 24,24 ) ); m_bitmap_find[index] = xpm.GetSubBitmap( wxRect(11 *24, 0, 24,24 ) ); m_bitmap_find_next[index] = xpm.GetSubBitmap( wxRect(12 *24, 0, 24,24 ) ); m_bitmap_move_down[index] = xpm.GetSubBitmap( wxRect(8 *24, 0, 24,24 ) ); m_bitmap_move_up[index] = xpm.GetSubBitmap( wxRect(7 *24, 0, 24,24 ) ); m_bitmap_new_download[index] = xpm.GetSubBitmap( wxRect(0 *24, 0, 24,24 ) ); m_bitmap_open_download_file[index] = xpm.GetSubBitmap( wxRect(4 *24, 0, 24,24 ) ); m_bitmap_options[index] = xpm.GetSubBitmap( wxRect(9 *24, 0, 24,24 ) ); m_bitmap_pause_download[index] = xpm.GetSubBitmap( wxRect(2 *24, 0, 24,24 ) ); m_bitmap_start_download[index] = xpm.GetSubBitmap( wxRect(1 *24, 0, 24,24 ) ); } void DownloadFrame::initializeCategoryTree() { } void DownloadFrame::initializeDownloadList() { } void DownloadFrame::on_new_download( wxCommandEvent& e ) { NewDownload* download = new NewDownload( this ); download->ShowModal(); } void DownloadFrame::on_add_batch_dwonload( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_launch_dwonload_file( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_browse_folder( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_check_for_file_update( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_download_again( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_start_download( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_pause_download( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_schedule_download( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_start_all_downloads( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_pause_all_downloads( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_import_download_list( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_import_broken_downloads( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_import_links_from_local_file( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_export_download_list( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_export_download_information( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_exit( wxCommandEvent& e ) { Close(); } void DownloadFrame::on_select_all_downloads( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_invert_selection( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_find_download( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_find_next_download( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_move_up( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_move_down( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_delete_download( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_move_to( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_copy_url_to_clipbroad( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_show_detail_panel( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_drop_zone_window( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_show_class_panel( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_export_download_file( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_rename_file( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_rename_commet_as_filename( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_new_category( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_move_category_to( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_delete_category( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_show_category_properties_window( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_new_database( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_open_database( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_merge_database( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_save_database( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_backup_to_database( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_imprt_previous_file_to_database( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_imprt_previous_batch_file_to_database( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_show_download_properties_window( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_show_properties_history_window( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_connect_or_disconnect( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_save_option_as_defauilt( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_show_option_window( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_goto_online_help( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_check_for_a_new_version( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_about( wxCommandEvent& e ) { e.Skip(); } void DownloadFrame::on_main_splitter_sash_position_changed( wxSplitterEvent& e ) { e.Skip(); }
[ "runner.mei@0dd8077a-353d-11de-b438-597f59cd7555" ]
[ [ [ 1, 328 ] ] ]
81ee3f42e87291ccb069227f95701b50903332df
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/mangalore/managers/focusmanager.cc
80722495d85f61a70f8985f9a5cb1b4d0a921c84
[]
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
10,908
cc
//------------------------------------------------------------------------------ // managers/focusmanager.cc // (C) 2005 Radon Labs GmbH //------------------------------------------------------------------------------ #include "managers/focusmanager.h" #include "properties/inputproperty.h" #include "properties/cameraproperty.h" #include "properties/videocameraproperty.h" #include "managers/entitymanager.h" #include "game/entity.h" namespace Managers { ImplementRtti(Managers::FocusManager, Game::Manager); ImplementFactory(Managers::FocusManager); FocusManager* FocusManager::Singleton = 0; using namespace Game; using namespace Properties; //------------------------------------------------------------------------------ /** */ FocusManager::FocusManager() { n_assert(0 == Singleton); Singleton = this; } //------------------------------------------------------------------------------ /** */ FocusManager::~FocusManager() { n_assert(!this->inputFocusEntity.isvalid()); n_assert(!this->cameraFocusEntity.isvalid()); n_assert(!this->newInputFocusEntity.isvalid()); n_assert(!this->newCameraFocusEntity.isvalid()); n_assert(Singleton); Singleton = 0; } //------------------------------------------------------------------------------ /** Sets the input and camera focus to the given entity. The entity pointer may be 0 to clear the input and camera focus. The entity must have both a InputProperty and CameraProperty attached, otherwise the method will fail. */ void FocusManager::SetFocusEntity(Entity* entity) { this->SetInputFocusEntity(entity); this->SetCameraFocusEntity(entity); } //------------------------------------------------------------------------------ /** Returns the current common focus entity. This method will fail if the current input focus entity and camera focus entity are not the same. The method may return 0 if there is no current focus entity. */ Entity* FocusManager::GetFocusEntity() const { if (this->cameraFocusEntity.isvalid()) { n_assert(this->cameraFocusEntity == this->inputFocusEntity); return this->cameraFocusEntity; } return 0; } //------------------------------------------------------------------------------ /** General "set focus to next entity". Can be camera and/or input focus. */ void FocusManager::SetToNextEntity(bool cameraFocus, bool inputFocus) { n_assert(cameraFocus || inputFocus); // get array of active entities const nArray<Ptr<Entity> >& entityArray = EntityManager::Instance()->GetEntities(); // get start entity nArray<Ptr<Entity> >::iterator iter = entityArray.Begin(); if (cameraFocus) { if (this->cameraFocusEntity.isvalid()) { iter = entityArray.Find(this->cameraFocusEntity); } } else { if (this->inputFocusEntity.isvalid()) { iter = entityArray.Find(this->inputFocusEntity); } } nArray<Ptr<Entity> >::iterator start = iter; if (iter) do { iter++; // wrap around if (iter == entityArray.End()) { iter = entityArray.Begin(); } Entity* entity = *iter; bool hasCameraProperty = (0 != entity->FindProperty(CameraProperty::RTTI)); bool hasInputProperty = (0 != entity->FindProperty(InputProperty::RTTI)); if (cameraFocus && inputFocus && hasCameraProperty && hasInputProperty) { this->SetFocusEntity(entity); return; } else if (cameraFocus && (!inputFocus) && hasCameraProperty) { this->SetCameraFocusEntity(entity); return; } else if (inputFocus && (!cameraFocus) && hasInputProperty) { this->SetInputFocusEntity(entity); return; } } while (iter != start); } //------------------------------------------------------------------------------ /** Set focus to next entity which has both an InputProperty and CameraProperty attached. If no current focus entity exists, the method will start to iterate with the first entity. The method will wrap around. The method will return false if no entities exist which have both an InputProperty and CameraProperty attached. */ void FocusManager::SetFocusToNextEntity() { this->SetToNextEntity(true, true); } //------------------------------------------------------------------------------ /** This method is called once per frame by the game server and actually handles focus entity switches. */ void FocusManager::OnFrame() { this->SwitchFocusEntities(); } //------------------------------------------------------------------------------ /** Actually switch focus entities. A focus entity switch doesn't happen immediately, but only once per frame. This is to prevent chain-reactions and circular reactions when 2 or more entities think they have the focus in a single frame. */ void FocusManager::SwitchFocusEntities() { if (this->newInputFocusEntity.isvalid()) { this->inputFocusEntity = this->newInputFocusEntity; this->newInputFocusEntity = 0; InputProperty* inputProp = (InputProperty*) this->inputFocusEntity->FindProperty(InputProperty::RTTI); n_assert(inputProp); inputProp->OnObtainFocus(); } if (this->newCameraFocusEntity.isvalid()) { this->cameraFocusEntity = this->newCameraFocusEntity; this->newCameraFocusEntity = 0; CameraProperty* cameraProp = (CameraProperty*) this->cameraFocusEntity->FindProperty(CameraProperty::RTTI); n_assert(cameraProp); cameraProp->OnObtainFocus(); } } //------------------------------------------------------------------------------ /** Set input focus entity to the given entity. The entity pointer can be 0, this will clear the current input focus. The entity must have an InputProperty attached for this to work. */ void FocusManager::SetInputFocusEntity(Entity* entity) { // clear input focus on all existing focus entities // (there may be cases where more then one entity has the input focus flag set, // mainly when a new level is loaded) EntityManager* entityManager = EntityManager::Instance(); int num = entityManager->GetNumEntities(); for (int i = 0; i < num; i++) { Entity* currEntity = entityManager->GetEntityAt(i); if (currEntity) { InputProperty* inputProperty = (InputProperty*) currEntity->FindProperty(InputProperty::RTTI); if (inputProperty && inputProperty->HasFocus()) { inputProperty->OnLoseFocus(); } } } this->inputFocusEntity = 0; this->newInputFocusEntity = entity; } //------------------------------------------------------------------------------ /** Get current input focus entity. This method may return 0 if no input focus entity is set. */ Entity* FocusManager::GetInputFocusEntity() const { return this->inputFocusEntity.get_unsafe(); } //------------------------------------------------------------------------------ /** Set input focus to the next entity which has an InputProperty attached. */ void FocusManager::SetInputFocusToNextEntity() { this->SetToNextEntity(false, true); } //------------------------------------------------------------------------------ /** Set camera focus entity to the given entity. The entity pointer can be 0, this will clear the current camera focus. The entity must have a CameraProperty attached for this to work. */ void FocusManager::SetCameraFocusEntity(Entity* entity) { // clear camera focus on all existing focus entities // (there may be cases where more then one entity has the camera focus flag set, // mainly when a new level is loaded) EntityManager* entityManager = EntityManager::Instance(); int num = entityManager->GetNumEntities(); for (int i = 0; i < num; i++) { Entity* currEntity = entityManager->GetEntityAt(i); if (currEntity) { CameraProperty* cameraProperty = (CameraProperty*) currEntity->FindProperty(CameraProperty::RTTI); if (cameraProperty && cameraProperty->HasFocus()) { cameraProperty->OnLoseFocus(); } } } this->cameraFocusEntity = 0; this->newCameraFocusEntity = entity; } //------------------------------------------------------------------------------ /** Get current camera focus entity. This method may return 0 if no input focus entity is set. */ Entity* FocusManager::GetCameraFocusEntity() const { return this->cameraFocusEntity.get_unsafe(); } //------------------------------------------------------------------------------ /** Set camera focus to next entity which has a CameraProperty attached. */ void FocusManager::SetCameraFocusToNextEntity() { this->SetToNextEntity(true, false); } //------------------------------------------------------------------------------ /** Set camera focus to first Entity with CameraFocus property. @result true, if proper entity found, false if not */ bool FocusManager::SwitchToFirstCameraFocusEntity() { const nArray<Ptr<Entity> >& entityArray = EntityManager::Instance()->GetEntities(); nArray<Ptr<Entity> >::iterator iter = entityArray.Begin(); bool priorityCameraFound = false; bool cameraPropertyEntityFound = false; while (iter != entityArray.End()) { Entity* entity = *iter; CameraProperty* cameraProperty = (CameraProperty*) entity->FindProperty(CameraProperty::RTTI); bool isPriorityCamera = (0 != entity->FindProperty(VideoCameraProperty::RTTI)); if (0 != cameraProperty) { if (cameraProperty->HasFocus()) cameraProperty->OnLoseFocus(); if (!cameraPropertyEntityFound || (!priorityCameraFound && isPriorityCamera)) { this->newCameraFocusEntity = entity; cameraPropertyEntityFound = true; priorityCameraFound = isPriorityCamera; } } iter++; } return cameraPropertyEntityFound; } //------------------------------------------------------------------------------ /** Set camera focus to first Entity with "GrabCameraFocus = true" or if none found to first "CameraFocus = true" Entity. */ void FocusManager::SetDefaultFocus() { SwitchToFirstCameraFocusEntity(); } } // namespace Managers
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 339 ] ] ]
49167fe3c8ec372531075671eb93d09f353cb6b2
a9aa7b62992b3eb3e8d724853fe5580f9294ac00
/src/LoadPlan.cpp
90ba61539e000b557db45c0d96def2bb664e22ea
[]
no_license
nwcfang/maiproj
7dd86743e193f73a6c92bee7e9f861ecc63fd271
313377dcc7908c64e11e322ec744d95b94cd2d4d
refs/heads/master
2016-09-06T12:27:31.080643
2011-12-23T09:58:14
2011-12-23T09:58:14
2,890,418
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
949
cpp
#include "LoadPlan.h" #include <stdio.h> // Функция загружает файл содержащий план пмещения // Вхоные параметры filename путь к файлу и имя файла // Возвращаемые значения: // 0 - успешное считывание // -1 - ошибка int LoadPlan::LoadMap(const char* filename) { FILE* f; for(int i = 0 ; i<PLANSIZE ;i++) for(int j = 0 ; j<PLANSIZE ;j++) { m[i][j] = 0;} if((f = fopen(filename,"r"))== NULL) return -1; for(int i = 0 ;i<PLANSIZE;i++) fgets(m[i],30,f); fclose(f); return 0; } char** LoadPlan::getMap() { char ** F ; F = new char*[PLANSIZE]; for(int i =0; i<PLANSIZE;i++) F[i]= new char[PLANSIZE]; for(int i =0; i<PLANSIZE;i++) for(int j =0; j<PLANSIZE;j++) F[i][j] = m[i][j]; return F; }
[ "nwcfang@nfl-home.(none)" ]
[ [ [ 1, 40 ] ] ]
0dcd5a77f2c3c2c6f9a8dba5d7b3a8082c14530c
62cd42ea3851a4e80a8e631ee02cc58433ac2731
/Descriptor.cpp
ba992104b50c3d2cff41d0663257e2a77ab7e2ec
[]
no_license
linuxts2epg/ts2epg
a0b84979b8437140843b7b07bc5cad25be3a2585
749f82a9412d94e39dd62570dfb7de2973f20a03
refs/heads/master
2020-05-20T11:28:52.982115
2008-09-07T15:06:36
2008-09-07T15:06:36
50,156
2
2
null
null
null
null
UTF-8
C++
false
false
2,178
cpp
/* * Descriptor.cpp * * Created on: 2008/09/04 * Author: linux_ts2epg */ #include "Descriptor.h" #include "DescriptorFactory.h" Descriptor::Descriptor() { // printf("Descriptor Default Constructor %x\n", this); } Descriptor::Descriptor(unsigned char *ptr, size_t length) { //printf("Descriptor Constructor %x\n", this); descriptorID = ptr[0]; descriptorLength = ptr[1]; memcpy(buf, ptr, descriptorLength + 2); buflen = descriptorLength + 2; } Descriptor::Descriptor(Descriptor &descriptor) { //printf("Descriptor Copy Constructor %x\n", this); descriptorID = descriptor.descriptorID; descriptorLength = descriptor.descriptorLength; buflen = descriptorLength + 2; memcpy(buf, descriptor.buf, buflen); } Descriptor::~Descriptor() { } unsigned char Descriptor::getDescriptorID() { return descriptorID; } unsigned char Descriptor::getDescriptorLength() { return descriptorLength; } void Descriptor::parseDescriptors(vector<Descriptor *> &descriptors, unsigned char *ptr, size_t descriptorsLoopLength, bool &hasError) { size_t processedByte = 0; while (processedByte < descriptorsLoopLength) { size_t descriptorLength = getDescriptorLengthByBuffer(ptr); Descriptor *descriptor = DescriptorFactory::create(ptr, descriptorLength + 2, hasError); // descriptor->printDescriptorBytes(); if (descriptor) descriptors.push_back(descriptor); processedByte += descriptorLength + 2; // printf("%d, %d\n", processedByte, descriptorsLoopLength); ptr += descriptorLength + 2; } if (processedByte != descriptorsLoopLength) { hasError = true; } } size_t Descriptor::getDescriptorLengthByBuffer(unsigned char *ptr) { return ptr[1]; } void Descriptor::printDescriptorBytes() { printf("DescriptorID = %02x, length=0x%02x(%d)\n", descriptorID, descriptorLength, descriptorLength); for (int i = 0; i < descriptorLength + 2; i++) { printf("%02x ", buf[i]); } printf("\n"); } unsigned char *Descriptor::getBufPtr() { return buf; } size_t Descriptor::getBufLen() { // printf("Descriptor(%x)::getBufLen()\n", this); return buflen; }
[ [ [ 1, 85 ] ] ]
4f5c2cfadef66207f3dae43654a60a72cd40db65
f8b364974573f652d7916c3a830e1d8773751277
/emulator/allegrex/disassembler/MAX.h
16a1572f2083511d470337acc88f37b2f6de7d80
[]
no_license
lemmore22/pspe4all
7a234aece25340c99f49eac280780e08e4f8ef49
77ad0acf0fcb7eda137fdfcb1e93a36428badfd0
refs/heads/master
2021-01-10T08:39:45.222505
2009-08-02T11:58:07
2009-08-02T11:58:07
55,047,469
0
0
null
null
null
null
UTF-8
C++
false
false
359
h
/* MAX */ void AllegrexInstructionTemplate< 0x0000002c, 0xfc0007ff >::disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment) { using namespace Allegrex; ::strcpy(opcode_name, "max"); ::sprintf(operands, "%s, %s, %s", gpr_name[rd(opcode)], gpr_name[rs(opcode)], gpr_name[rt(opcode)]); ::strcpy(comment, ""); }
[ [ [ 1, 9 ] ] ]
4e718afbbd44946b60ca275e7d73a938166847ee
8ad5d6836fe4ad3349929802513272db86d15bc3
/lib/Spin/Handlers/NewDataHandler.h
fffd2b8a7447a726457491eeec69c22bc8b48808
[]
no_license
blytkerchan/arachnida
90a72c27f0c650a6fbde497896ef32186c0219e5
468f4ef6c35452de3ca026af42b8eedcef6e4756
refs/heads/master
2021-01-10T21:43:51.505486
2010-03-12T04:02:19
2010-03-12T04:02:42
2,203,393
0
1
null
null
null
null
UTF-8
C++
false
false
656
h
#ifndef _spin_handlers_newdatahandler_h #define _spin_handlers_newdatahandler_h #include "../Details/prologue.h" #include <boost/shared_ptr.hpp> namespace Spin { class Connection; namespace Handlers { //! Handler for when new data is ready on a connection class SPIN_API NewDataHandler { public : const NewDataHandler & operator()(boost::shared_ptr< Connection > connection) { onDataReady(connection); return *this; } protected : virtual ~NewDataHandler(); //! Called when new data is ready. virtual void onDataReady(boost::shared_ptr< Connection > connection) = 0; }; } } #endif
[ [ [ 1, 4 ], [ 6, 15 ], [ 17, 24 ], [ 26, 30 ] ], [ [ 5, 5 ], [ 16, 16 ], [ 25, 25 ] ] ]
27107ba95b59c6fdf78ecc405ed8ee8c7df35c8f
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/framework/psvi/XSMultiValueFacet.cpp
875237d8e8c32f21c93f1f264aca6fa2b2223504
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
3,459
cpp
/* * Copyright 2003,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Log: XSMultiValueFacet.cpp,v $ * Revision 1.8 2004/09/08 13:56:08 peiyongz * Apache License Version 2.0 * * Revision 1.7 2003/12/15 17:23:48 cargilld * psvi updates; cleanup revisits and bug fixes * * Revision 1.6 2003/11/27 16:42:00 neilg * fixes for segfaults and infinite loops in schema component model implementation; thanks to David Cargill * * Revision 1.5 2003/11/21 17:34:04 knoaman * PSVI update * * Revision 1.4 2003/11/14 22:47:53 neilg * fix bogus log message from previous commit... * * Revision 1.3 2003/11/14 22:33:30 neilg * Second phase of schema component model implementation. * Implement XSModel, XSNamespaceItem, and the plumbing necessary * to connect them to the other components. * Thanks to David Cargill. * * Revision 1.2 2003/11/06 15:30:04 neilg * first part of PSVI/schema component model implementation, thanks to David Cargill. This covers setting the PSVIHandler on parser objects, as well as implementing XSNotation, XSSimpleTypeDefinition, XSIDCDefinition, and most of XSWildcard, XSComplexTypeDefinition, XSElementDeclaration, XSAttributeDeclaration and XSAttributeUse. * * Revision 1.1 2003/09/16 14:33:36 neilg * PSVI/schema component model classes, with Makefile/configuration changes necessary to build them * */ #include <xercesc/framework/psvi/XSMultiValueFacet.hpp> #include <xercesc/framework/psvi/XSAnnotation.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // XSMultiValueFacet: Constructors and Destructors // --------------------------------------------------------------------------- XSMultiValueFacet::XSMultiValueFacet(XSSimpleTypeDefinition::FACET facetKind, StringList* lexicalValues, bool isFixed, XSAnnotation* const headAnnot, XSModel* const xsModel, MemoryManager* const manager) : XSObject(XSConstants::MULTIVALUE_FACET, xsModel, manager) , fFacetKind(facetKind) , fIsFixed(isFixed) , fLexicalValues(lexicalValues) , fXSAnnotationList(0) { if (headAnnot) { fXSAnnotationList = new (manager) RefVectorOf<XSAnnotation>(1, false, manager); XSAnnotation* annot = headAnnot; do { fXSAnnotationList->addElement(annot); annot = annot->getNext(); } while (annot); } } XSMultiValueFacet::~XSMultiValueFacet() { if (fXSAnnotationList) delete fXSAnnotationList; } XERCES_CPP_NAMESPACE_END
[ [ [ 1, 90 ] ] ]
5a37c79e5836b8cdce3a63a6a5ee5d335c82d989
1193b8d2ab6bb40ce2adbf9ada5b3d1124f1abb3
/trunk/libsonetto/include/SonettoFontSerializer.h
ce5592efaa639a04aab0c2b58f57321f2d14b428
[]
no_license
sonetto/legacy
46bb60ef8641af618d22c08ea198195fd597240b
e94a91950c309fc03f9f52e6bc3293007c3a0bd1
refs/heads/master
2021-01-01T16:45:02.531831
2009-09-10T21:50:42
2009-09-10T21:50:42
32,183,635
0
2
null
null
null
null
UTF-8
C++
false
false
2,381
h
/*----------------------------------------------------------------------------- Copyright (c) 2009, Sonetto Project Developers 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. Neither the name of the Sonetto Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -----------------------------------------------------------------------------*/ #ifndef SONETTO_FONTSERIALIZER_H #define SONETTO_FONTSERIALIZER_HFont #include <OgreSerializer.h> #include "SonettoPrerequisites.h" namespace Sonetto { class Font; // forward declaration class SONETTO_API FontSerializer : public Ogre::Serializer { public: FontSerializer(); virtual ~FontSerializer(); void exportFont(const Font *pFont, const Ogre::String &fileName); void importFont(Ogre::DataStreamPtr &stream, Font *pDest); std::string loadString(Ogre::DataStreamPtr& stream); void saveString(const std::string &str); }; }; // namespace #endif // SONETTO_FONTSERIALIZER_H
[ [ [ 1, 55 ] ] ]
d6581fd7cf2fbae0992bb00bd6a64f93160fd12a
54cacc105d6bacdcfc37b10d57016bdd67067383
/trunk/source/level/objects/components/CmpCharacterModelRender.cpp
9f5779ca92ff3c04e11f89b487d3db967d0d41c4
[]
no_license
galek/hesperus
4eb10e05945c6134901cc677c991b74ce6c8ac1e
dabe7ce1bb65ac5aaad144933d0b395556c1adc4
refs/heads/master
2020-12-31T05:40:04.121180
2009-12-06T17:38:49
2009-12-06T17:38:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,552
cpp
/*** * hesperus: CmpCharacterModelRender.cpp * Copyright Stuart Golodetz, 2009. All rights reserved. ***/ #include "CmpCharacterModelRender.h" #include <source/ogl/WrappedGL.h> #include <source/axes/NUVAxes.h> #include <source/level/models/AnimationController.h> #include <source/level/models/Model.h> #include <source/level/models/Skeleton.h> #include <source/math/matrices/RBTMatrix.h> #include <source/util/Properties.h> #include "ICmpAnimChooser.h" #include "ICmpBasicModelRender.h" #include "ICmpInventory.h" #include "ICmpOrientation.h" #include "ICmpOwnable.h" #include "ICmpSimulation.h" namespace hesp { //#################### CONSTRUCTORS #################### CmpCharacterModelRender::CmpCharacterModelRender(const BoneModifierMap& inclineBones, const std::string& modelName) : CmpModelRender(modelName), m_inclineBones(inclineBones) {} //#################### STATIC FACTORY METHODS #################### IObjectComponent_Ptr CmpCharacterModelRender::load(const Properties& properties) { return IObjectComponent_Ptr(new CmpCharacterModelRender( properties.get<BoneModifierMap>("InclineBones"), properties.get<std::string>("ModelName") )); } //#################### PUBLIC METHODS #################### void CmpCharacterModelRender::check_dependencies() const { check_dependency<ICmpAnimChooser>(); check_dependency<ICmpInventory>(); check_dependency<ICmpOrientation>(); check_dependency<ICmpSimulation>(); } void CmpCharacterModelRender::render() const { ICmpOrientation_CPtr cmpOrientation = m_objectManager->get_component(m_objectID, cmpOrientation); ICmpPosition_CPtr cmpPosition = m_objectManager->get_component(m_objectID, cmpPosition); const Vector3d& p = cmpPosition->position(); const Vector3d& n = cmpOrientation->nuv_axes()->n(); const Vector3d& u = cmpOrientation->nuv_axes()->u(); const Vector3d& v = cmpOrientation->nuv_axes()->v(); if(m_modelPose != NULL) { RBTMatrix_CPtr mat = construct_model_matrix(p, n, u, v); glPushMatrix(); glMultMatrixd(&mat->rep()[0]); // Render the model. model()->render(m_modelPose); // Render the active item (if any). ICmpInventory_Ptr cmpInventory = m_objectManager->get_component(m_objectID, cmpInventory); assert(cmpInventory); ObjectID activeItem = cmpInventory->active_item(); if(activeItem.valid()) { ICmpBasicModelRender_Ptr cmpItemRender = m_objectManager->get_component(activeItem, cmpItemRender); if(cmpItemRender) { cmpItemRender->render_child(); } } glPopMatrix(); } if(m_highlights) { // If the object should be highlighted, render the object's bounds. render_bounds(p); } // Render the object's NUV axes. render_nuv_axes(p, n, u, v); } void CmpCharacterModelRender::render_first_person() const { ICmpInventory_Ptr cmpInventory = m_objectManager->get_component(m_objectID, cmpInventory); assert(cmpInventory); ObjectID activeItem = cmpInventory->active_item(); if(!activeItem.valid()) return; ICmpBasicModelRender_Ptr cmpItemRender = m_objectManager->get_component(activeItem, cmpItemRender); if(!cmpItemRender) return; cmpItemRender->render_first_person(); render_crosshair(); } Properties CmpCharacterModelRender::save() const { Properties properties; properties.set("InclineBones", m_inclineBones); properties.set("ModelName", m_modelName); return properties; } void CmpCharacterModelRender::update_animation(int milliseconds, const std::vector<CollisionPolygon_Ptr>& polygons, const OnionTree_CPtr& tree, const NavManager_CPtr& navManager) { // Decide which animation should be playing, and update it. ICmpAnimChooser_Ptr cmpAnimChooser = m_objectManager->get_component(m_objectID, cmpAnimChooser); assert(cmpAnimChooser); m_animController->request_animation(cmpAnimChooser->choose_animation(polygons, tree, navManager)); m_animController->update(milliseconds); // Clear any existing pose modifiers. m_animController->clear_pose_modifiers(); // Determine the animation extension of any carried item in order to determine which bones need to be inclined. std::string animExtension = ""; // the explicit initialisation is to make it clear that "" is the default ICmpInventory_Ptr cmpInventory = m_objectManager->get_component(m_objectID, cmpInventory); assert(cmpInventory); ObjectID activeItem = cmpInventory->active_item(); if(activeItem.valid()) { ICmpOwnable_Ptr cmpItemOwnable = m_objectManager->get_component(activeItem, cmpItemOwnable); assert(cmpItemOwnable); animExtension = cmpItemOwnable->anim_extension(); } // Calculate the inclination of the object's coordinate system and apply pose modifiers to the relevant bones. BoneModifierMap::const_iterator it = m_inclineBones.find(animExtension); if(it != m_inclineBones.end()) { ICmpOrientation_Ptr cmpOrientation = m_objectManager->get_component(m_objectID, cmpOrientation); const Vector3d& n = cmpOrientation->nuv_axes()->n(); double sinInclination = n.z / n.length(); if(sinInclination < -1) sinInclination = -1; if(sinInclination > 1) sinInclination = 1; double inclination = asin(sinInclination); for(std::map<std::string,Vector3d>::const_iterator jt=it->second.begin(), jend=it->second.end(); jt!=jend; ++jt) { m_animController->set_pose_modifier(jt->first, PoseModifier(jt->second, -inclination)); } } // Configure the pose. m_modelPose = model()->configure_pose(m_animController); // Update the animation for the active item (if any), e.g. the weapon being carried. if(activeItem.valid()) { ICmpOrientation_CPtr cmpOrientation = m_objectManager->get_component(m_objectID, cmpOrientation); ICmpPosition_CPtr cmpPosition = m_objectManager->get_component(m_objectID, cmpPosition); const Vector3d& p = cmpPosition->position(); const Vector3d& n = cmpOrientation->nuv_axes()->n(); const Vector3d& u = cmpOrientation->nuv_axes()->u(); const Vector3d& v = cmpOrientation->nuv_axes()->v(); RBTMatrix_CPtr modelMatrix = construct_model_matrix(p, n, u, v); ICmpOwnable_Ptr cmpItemOwnable = m_objectManager->get_component(activeItem, cmpItemOwnable); assert(cmpItemOwnable); ICmpBasicModelRender_Ptr cmpItemRender = m_objectManager->get_component(activeItem, cmpItemRender); if(cmpItemRender) { cmpItemRender->update_child_animation(milliseconds, skeleton()->bone_hierarchy(), cmpItemOwnable->attach_point(), modelMatrix, polygons, tree, navManager); } } } //#################### PRIVATE METHODS #################### RBTMatrix_CPtr CmpCharacterModelRender::construct_model_matrix(const Vector3d& p, const Vector3d& n, const Vector3d& u, const Vector3d& v) { // Note: The vertical axis of a character model does not rotate, unlike that for a // normal model. In other words, looking up/down should have no effect on the // way the model is rendered in this case (e.g. the character's head stays above // its feet, for biped models). This necessitates the modified model matrix // shown below. // Project u and n into the horizontal plane (i.e. z = 0) to form uH and nH respectively. // Note that the camera is prevented from ever pointing directly upwards/downwards, so // renormalizing the resulting vectors isn't a problem. Vector3d uH = u; uH.z = 0; uH.normalize(); Vector3d nH = n; nH.z = 0; nH.normalize(); // Note: This matrix maps x -> uH, -y -> nH, z -> z, and translates by p. Since models are // built in Blender facing in the -y direction, this turns out to be exactly the // transformation required to render the models with the correct position and // orientation. RBTMatrix_Ptr mat = RBTMatrix::zeros(); RBTMatrix& m = *mat; m(0,0) = uH.x; m(0,1) = -nH.x; /*m(0,2) = 0;*/ m(0,3) = p.x; m(1,0) = uH.y; m(1,1) = -nH.y; /*m(1,2) = 0;*/ m(1,3) = p.y; /*m(2,0) = 0;*/ /*m(2,1) = 0;*/ m(2,2) = 1; m(2,3) = p.z; return mat; } void CmpCharacterModelRender::render_crosshair() { glPushMatrix(); glPushAttrib(GL_ENABLE_BIT); glLoadIdentity(); glDisable(GL_DEPTH_TEST); // disable z-buffer testing glDisable(GL_DEPTH_WRITEMASK); // disable z-buffer writing const double Z_OFFSET = 30; glColor3d(1,1,1); glBegin(GL_LINES); glVertex3d(-1,0,-Z_OFFSET); glVertex3d(1,0,-Z_OFFSET); glVertex3d(0,-1,-Z_OFFSET); glVertex3d(0,1,-Z_OFFSET); glEnd(); glPopAttrib(); glPopMatrix(); } }
[ [ [ 1, 230 ] ] ]
04688a3d035640914474fb123790893cd9bc0b27
2e19f081741da056cd54a3abb4ced24b860a6173
/vector.h
8e15705003233d62d683f51b237de3273c25a205
[]
no_license
afxgroup/newscoasteros4
000e2a80a21d073da8514da23a180150ff40b663
56402499015ca87ef32754b19866c565d606a2a1
refs/heads/master
2020-04-05T03:51:05.185487
2009-07-28T13:36:41
2009-07-28T13:36:41
32,485,849
0
0
null
null
null
null
UTF-8
C++
false
false
2,412
h
//#define DoMethod(obj,...) obj==null ? printf("%s : %d NULL OBJECT!!!\n",__FILE__,__LINE__) : DoMethod(x,...); class Vector { int capacity; int size; void ** data; public: Vector(int capacity); Vector(); ~Vector(); void ** getData() { return data; } int getSize(); void add(void * element); void *getElementAt(int i); void removeElement(void * element); void removeElementAt(int i); void flush(); }; //#define _DEBUG #ifdef _DEBUG class Vector; class AllocInfo { public: unsigned int address; unsigned int size; char file[256]; int line; static Vector allocs; AllocInfo(unsigned int address,unsigned int size, const char *file, int line); }; //void AddTrack(DWORD ptr, unsigned int size, const char *file, int line); void AddTrack(unsigned int ptr, unsigned int size, const char *file, int line) { AllocInfo *allocInfo = new AllocInfo(ptr,size,file,line); AllocInfo::allocs.add(allocInfo); } BOOL RemoveTrack(unsigned int ptr,int size); void dumpAllocs(); inline void * /*__cdecl*/ operator new(unsigned int size, const char *file, int line) { void *ptr = (void *)malloc(size); AddTrack((unsigned int)ptr, size, file, line); return(ptr); }; /*inline void * operator new[](unsigned int size, const char *file, int line) { void *ptr = (void *)malloc(size); AddTrack((unsigned int)ptr, size, file, line); return(ptr); };*/ inline void operator delete(void *ptr, size_t size) { RemoveTrack((unsigned int)ptr,size); free(ptr); }; /*inline void operator delete[](void *ptr) { RemoveTrack((unsigned int)ptr); free(ptr); };*/ //inline void * malloc_track(unsigned int size) { inline void * malloc_track(unsigned int size, const char *file, int line) { void *ptr = (void *)malloc(size); AddTrack((unsigned int)ptr, size, file, line); //AddTrack((DWORD)ptr, size, "unknown", -1); return(ptr); }; inline void free_track(void *ptr) { RemoveTrack((unsigned int)ptr,-1); free(ptr); }; #endif #ifdef _DEBUG #define DEBUG_NEW new(__FILE__, __LINE__) #define malloc( x ) malloc_track( x, __FILE__, __LINE__ ) #define free free_track #else #define DEBUG_NEW new #endif #define new DEBUG_NEW
[ "andrea.palmate@44b1b908-7b79-11de-a7be-13e53affbef8" ]
[ [ [ 1, 87 ] ] ]
eae64138d5eae7a4f3fd58e5558dd1ba45258ff0
3ecc6321b39e2aedb14cb1834693feea24e0896f
/src/plane.cpp
e6f4f6fdd0ae8f1b6d5acb7041764d834b2c2edf
[]
no_license
weimingtom/forget3d
8c1d03aa60ffd87910e340816d167c6eb537586c
27894f5cf519ff597853c24c311d67c7ce0aaebb
refs/heads/master
2021-01-10T02:14:36.699870
2011-06-24T06:21:14
2011-06-24T06:21:14
43,621,966
1
1
null
null
null
null
UTF-8
C++
false
false
5,651
cpp
/***************************************************************************** * Copyright (C) 2009 The Forget3D Project by Martin Foo ([email protected]) * ALL RIGHTS RESERVED * * License I * Permission to use, copy, modify, and distribute this software for * any purpose and WITHOUT a fee is granted under following requirements: * - You make no money using this software. * - The authors and/or this software is credited in your software or any * work based on this software. * * Licence II * Permission to use, copy, modify, and distribute this software for * any purpose and WITH a fee is granted under following requirements: * - As soon as you make money using this software, you have to pay a * licence fee. Until this point of time, you can use this software * without a fee. * Please contact Martin Foo ([email protected]) for further details. * - The authors and/or this software is credited in your software or any * work based on this software. * * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS" * AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, * INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR * FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHORS * BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER, * INCLUDING WITHOUT LIMITATION, LOSS OF PROFIT, LOSS OF USE, SAVINGS OR * REVENUE, OR THE CLAIMS OF THIRD PARTIES, WHETHER OR NOT THE AUTHORS HAVE * BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE * POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE. *****************************************************************************/ #include "plane.h" namespace F3D { /** * Plane class for all games using F3D. */ Plane::Plane(int width, int height, float scale) { int vt_idx = 0, nm_idx = 0, uv_idx = 0; float *vertices = (float *) malloc(width * height * 18 * sizeof(float)); float *normals = (float *) malloc(width * height * 18 * sizeof(float)); float *uvs = (float *) malloc(width * height * 12 * sizeof(float)); #ifdef DEBUG printf("Plane constructor...\n"); #endif setMeshCount(1); for (int x = 0; x < width; x++) { for (int z = 0; z < height; z++) { //triangle 1 first point vertices[vt_idx++] = x * scale; vertices[vt_idx++] = 0.0f; vertices[vt_idx++] = z * scale; normals[nm_idx++] = 0.0f; normals[nm_idx++] = 1.0f; normals[nm_idx++] = 0.0f; uvs[uv_idx++] = 0.0f; uvs[uv_idx++] = 0.0f; //second point vertices[vt_idx++] = (x + 1) * scale; vertices[vt_idx++] = 0.0f; vertices[vt_idx++] = z * scale; normals[nm_idx++] = 0.0f; normals[nm_idx++] = 1.0f; normals[nm_idx++] = 0.0f; uvs[uv_idx++] = 1.0f; uvs[uv_idx++] = 0.0f; //third point vertices[vt_idx++] = (x + 1) * scale; vertices[vt_idx++] = 0.0f; vertices[vt_idx++] = (z + 1) * scale; normals[nm_idx++] = 0.0f; normals[nm_idx++] = 1.0f; normals[nm_idx++] = 0.0f; uvs[uv_idx++] = 1.0f; uvs[uv_idx++] = 1.0f; //triangle 1 first point vertices[vt_idx++] = x * scale; vertices[vt_idx++] = 0.0f; vertices[vt_idx++] = z * scale; normals[nm_idx++] = 0.0f; normals[nm_idx++] = 1.0f; normals[nm_idx++] = 0.0f; uvs[uv_idx++] = 0.0f; uvs[uv_idx++] = 0.0f; //third point vertices[vt_idx++] = (x + 1) * scale; vertices[vt_idx++] = 0.0f; vertices[vt_idx++] = (z + 1) * scale; normals[nm_idx++] = 0.0f; normals[nm_idx++] = 1.0f; normals[nm_idx++] = 0.0f; uvs[uv_idx++] = 1.0f; uvs[uv_idx++] = 1.0f; //fourth pint vertices[vt_idx++] = x * scale; vertices[vt_idx++] = 0.0f; vertices[vt_idx++] = (z + 1) * scale; normals[nm_idx++] = 0.0f; normals[nm_idx++] = 1.0f; normals[nm_idx++] = 0.0f; uvs[uv_idx++] = 0.0f; uvs[uv_idx++] = 1.0f; } } //set data to model setVertices(vertices, width * height * 18 * sizeof(float)); setNormals(normals, width * height * 18 * sizeof(float)); setUvs(uvs, width * height * 12 * sizeof(float)); setTriangleNums(width * height * 2); FREEANDNULL(vertices); FREEANDNULL(uvs); FREEANDNULL(normals); #ifdef DEBUG printf("Generate plane OK!\n"); #endif } Plane::~Plane() { #ifdef DEBUG printf("Plane destructor...\n"); #endif } void Plane::prepareFrame() { #ifdef DEBUG static bool isFirst = true; if (isFirst) { printf("Call Plane::prepareFrame()...\n"); isFirst = false; } #endif } }
[ "i25ffz@8907dee8-4f14-11de-b25e-a75f7371a613" ]
[ [ [ 1, 154 ] ] ]
af1ae3f2a89e67a6c0815f4cfe54eb3988dcf3bf
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/websrv/web_service_description_api/inc/SenServDescBCTest.h
11de815a969fb80f60d0fb667a4975f756439696
[]
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
20,038
h
/* * Copyright (c) 2002 - 2007 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: SenServDesc test module. * */ #ifndef SENSERVDESCBCTEST_H #define SENSERVDESCBCTEST_H // INCLUDES #include "StifTestModule.h" #include <StifLogger.h> #include <flogger.h> #include <SenBaseAttribute.h> #include <SenBaseElement.h> #include <SenBaseFragment.h> //#include <SenConsumerPolicy.h> #include <SenCredential.h> #include <SenDomFragment.h> #include <SenFacet.h> #include <SenIdentityProvider.h> #include <SenIdentityProviderIdArray8.h> #include <SenNamespace.h> //#include <SenPolicy.h> //#include <SenProviderPolicy.h> #include <SenServicePattern.h> #include <SenSoapEnvelope.h> #include <SenXmlReader.h> #include <SenXmlServiceDescription.h> #include <MSenIdentityProviderIdArray.h> #include <SenDateUtils.h> #include <SenXmlUtils.h> #include <SenXmlConstants.h> #include <e32debug.h> class CSenConsumerPolicy; class CSenBaseElement; class CSenBaseFragment; class CSenIdentityProvider; class CSenIdentityProviderIdArray8; class CSenSoapEnvelope; class CSenPolicy; class CSenCredential; class CSenBaseAttribute; class CSenServicePattern; class CSenDomFragment; class CSenNamespace; class CSenFacet; class MSenIdentityProviderIdArray; class CSenXmlReader; class CSenXmlServiceDescription; class CSenProviderPolicy; class SenXmlUtils; class SenDateUtils; // CONSTANTS //const ?type ?constant_var = ?constant; // MACROS //#define ?macro ?macro_def #define TEST_MODULE_VERSION_MAJOR 51 #define TEST_MODULE_VERSION_MINOR 9 #define TEST_MODULE_VERSION_BUILD 38 namespace{ _LIT8(KText,"text"); _LIT8(KText2,"text2"); _LIT8(KXmlSpecific, "\"&<>"); } // Logging path _LIT( KSenServDescLogPath, "\\logs\\testframework\\SenServDesc\\" ); // Log file _LIT( KSenServDescLogFile, "SenServDesc.txt" ); #define GETPTR & #define ENTRY(str,func) {_S(str), GETPTR func,0,0,0} #define FUNCENTRY(func) {_S(#func), GETPTR func,0,0,0} #define OOM_ENTRY(str,func,a,b,c) {_S(str), GETPTR func,a,b,c} #define OOM_FUNCENTRY(func,a,b,c) {_S(#func), GETPTR func,a,b,c} // FUNCTION PROTOTYPES //?type ?function_name(?arg_list); // FORWARD DECLARATIONS //class ?FORWARD_CLASSNAME; class CSenServDesc; // DATA TYPES //enum ?declaration //typedef ?declaration //extern ?data_type; // A typedef for function that does the actual testing, // function is a type // TInt CSenServDesc::<NameOfFunction> ( TTestResult& aResult ) typedef TInt (CSenServDesc::* TestFunction)(TTestResult&); // CLASS DECLARATION /** * An internal structure containing a test case name and * the pointer to function doing the test * * @lib ?library * @since ?Series60_version */ class TCaseInfoInternal { public: const TText* iCaseName; TestFunction iMethod; TBool iIsOOMTest; TInt iFirstMemoryAllocation; TInt iLastMemoryAllocation; }; // CLASS DECLARATION /** * A structure containing a test case name and * the pointer to function doing the test * * @lib ?library * @since ?Series60_version */ class TCaseInfo { public: TPtrC iCaseName; TestFunction iMethod; TBool iIsOOMTest; TInt iFirstMemoryAllocation; TInt iLastMemoryAllocation; TCaseInfo( const TText* a ) : iCaseName( (TText*) a ) { }; }; // CLASS DECLARATION /** * This a SenServDesc class. * ?other_description_lines * * @lib ?library * @since ?Series60_version */ NONSHARABLE_CLASS(CSenServDesc) : public CTestModuleBase { public: // Constructors and destructor /** * Two-phased constructor. */ static CSenServDesc* NewL(); /** * Destructor. */ virtual ~CSenServDesc(); public: // New functions /** * ?member_description. * @since ?Series60_version * @param ?arg1 ?description * @return ?description */ //?type ?member_function( ?type ?arg1 ); public: // Functions from base classes /** * From CTestModuleBase InitL is used to initialize the * SenServDesc. It is called once for every instance of * TestModuleSenServDesc after its creation. * @since ?Series60_version * @param aIniFile Initialization file for the test module (optional) * @param aFirstTime Flag is true when InitL is executed for first * created instance of SenServDesc. * @return Symbian OS error code */ TInt InitL( TFileName& aIniFile, TBool aFirstTime ); /** * From CTestModuleBase GetTestCasesL is used to inquiry test cases * from SenServDesc. * @since ?Series60_version * @param aTestCaseFile Test case file (optional) * @param aTestCases Array of TestCases returned to test framework * @return Symbian OS error code */ TInt GetTestCasesL( const TFileName& aTestCaseFile, RPointerArray<TTestCaseInfo>& aTestCases ); /** * From CTestModuleBase RunTestCaseL is used to run an individual * test case. * @since ?Series60_version * @param aCaseNumber Test case number * @param aTestCaseFile Test case file (optional) * @param aResult Test case result returned to test framework (PASS/FAIL) * @return Symbian OS error code (test case execution error, which is * not reported in aResult parameter as test case failure). */ TInt RunTestCaseL( const TInt aCaseNumber, const TFileName& aTestCaseFile, TTestResult& aResult ); /** * From CTestModuleBase; OOMTestQueryL is used to specify is particular * test case going to be executed using OOM conditions * @param aTestCaseFile Test case file (optional) * @param aCaseNumber Test case number (optional) * @param aFailureType OOM failure type (optional) * @param aFirstMemFailure The first heap memory allocation failure value (optional) * @param aLastMemFailure The last heap memory allocation failure value (optional) * @return TBool */ virtual TBool OOMTestQueryL( const TFileName& /* aTestCaseFile */, const TInt /* aCaseNumber */, TOOMFailureType& aFailureType, TInt& /* aFirstMemFailure */, TInt& /* aLastMemFailure */ ); /** * From CTestModuleBase; OOMTestInitializeL may be used to initialize OOM * test environment * @param aTestCaseFile Test case file (optional) * @param aCaseNumber Test case number (optional) * @return None */ virtual void OOMTestInitializeL( const TFileName& /* aTestCaseFile */, const TInt /* aCaseNumber */ ); /** * From CTestModuleBase; OOMHandleWarningL * @param aTestCaseFile Test case file (optional) * @param aCaseNumber Test case number (optional) * @param aFailNextValue FailNextValue for OOM test execution (optional) * @return None * * User may add implementation for OOM test warning handling. Usually no * implementation is required. */ virtual void OOMHandleWarningL( const TFileName& /* aTestCaseFile */, const TInt /* aCaseNumber */, TInt& /* aFailNextValue */); /** * From CTestModuleBase; OOMTestFinalizeL may be used to finalize OOM * test environment * @param aTestCaseFile Test case file (optional) * @param aCaseNumber Test case number (optional) * @return None * */ virtual void OOMTestFinalizeL( const TFileName& /* aTestCaseFile */, const TInt /* aCaseNumber */ ); /** * Method used to log version of test module */ void SendTestModuleVersion(); protected: // New functions /** * ?member_description. * @since ?Series60_version * @param ?arg1 ?description * @return ?description */ //?type ?member_function( ?type ?arg1 ); protected: // Functions from base classes /** * From ?base_class ?member_description */ //?type ?member_function(); private: /** * C++ default constructor. */ CSenServDesc(); /** * By default Symbian 2nd phase constructor is private. */ void ConstructL(); // Prohibit copy constructor if not deriving from CBase. // ?classname( const ?classname& ); // Prohibit assigment operator if not deriving from CBase. // ?classname& operator=( const ?classname& ); /** * Function returning test case name and pointer to test case function. * @since ?Series60_version * @param aCaseNumber test case number * @return TCaseInfo */ const TCaseInfo Case ( const TInt aCaseNumber ) const; private: // New methods void SetupL(); void Teardown(); TPtr16 ConvertToPtr16LC(CSenBaseFragment &fragment); TPtr16 ConvertToPtr16LC(CSenBaseElement &element); TInt MT_CSenConsumerPolicy_NewLL( TTestResult& aResult ); TInt MT_CSenConsumerPolicy_NewLCL(TTestResult& aResult); TInt MT_CSenConsumerPolicy_NewL_1L(TTestResult& aResult); TInt MT_CSenConsumerPolicy_NewLC_1L(TTestResult& aResult); void MT_CSenConsumerPolicy_RebuildFromL(); void MT_CSenConsumerPolicy_AcceptsL(); TInt MT_CSenCredential_NewLL(TTestResult& aResult); TInt MT_CSenCredential_NewLCL(TTestResult& aResults); TInt MT_CSenCredential_NewL_1L(TTestResult& aResult); TInt MT_CSenCredential_NewLC_1L(TTestResult& aResult); TInt MT_CSenCredential_NewL_2L(TTestResult& aResult); TInt MT_CSenCredential_NewLC_2L(TTestResult& aResult); void MT_CSenCredential_IdL(); void MT_CSenCredential_ValidUntilL(); void MT_CSenCredential_SetValidUntilL(); TInt MT_CSenFacet_NewLL( TTestResult& aResult ); TInt MT_CSenFacet_NewL_1L(TTestResult& aResult); TInt MT_CSenFacet_NewL_2L(TTestResult& aResult); TInt MT_CSenFacet_SetNameLL( TTestResult& aResult ); TInt MT_CSenFacet_SetTypeLL(TTestResult& aResult); TInt MT_CSenFacet_SetValueLL(TTestResult& aResult); TInt MT_CSenFacet_NameL(TTestResult& aResult); TInt MT_CSenFacet_TypeL(TTestResult& aResult); TInt MT_CSenFacet_ValueL(TTestResult& aResult); void MT_CSenIdentityProvider_NewLL(); TInt MT_CSenIdentityProvider_NewLCL( TTestResult& aResult ); TInt MT_CSenIdentityProvider_NewL_1L(TTestResult& aResult); TInt MT_CSenIdentityProvider_NewLC_1L(TTestResult& aResult); TInt MT_CSenIdentityProvider_NewL_2L(TTestResult& aResult); TInt MT_CSenIdentityProvider_NewLC_2L(TTestResult& aResult); TInt MT_CSenIdentityProvider_NewL_3L(TTestResult& aResult); TInt MT_CSenIdentityProvider_NewLC_3L(TTestResult& aResult); TInt MT_CSenIdentityProvider_AuthzIDL(TTestResult& aResult); TInt MT_CSenIdentityProvider_AdvisoryAuthnIDL(TTestResult& aResult); TInt MT_CSenIdentityProvider_ProviderIDL(TTestResult& aResult); TInt MT_CSenIdentityProvider_PasswordL(TTestResult& aResult); TInt MT_CSenIdentityProvider_IMEIL(TTestResult& aResult); TInt MT_CSenIdentityProvider_UserNameL(TTestResult& aResult); TInt MT_CSenIdentityProvider_SetProviderIDL(TTestResult& aResult); TInt MT_CSenIdentityProvider_SetServiceIDL(TTestResult& aResult); void MT_CSenIdentityProvider_IsTrustedByLL(); void MT_CSenIdentityProvider_IsTrustedByL_1L(); void MT_CSenIdentityProvider_IsDefaultL(); void MT_CSenIdentityProvider_SetUserInfoLL(); TInt MT_CSenIdentityProvider_HttpCredentialsLL(TTestResult& aResult); TInt MT_CSenIdentityProvider_NewElementNameL(TTestResult& aResult); TInt MT_CSenIdentityProviderIdArray8_NewLL(TTestResult& aResult); TInt MT_CSenIdentityProviderIdArray8_NewLCL(TTestResult& aResult); TInt MT_CSenIdentityProviderIdArray8_NewL_1L(TTestResult& aResult); TInt MT_CSenIdentityProviderIdArray8_NewLC_1L(TTestResult& aResult); TInt MT_CSenIdentityProviderIdArray8_IsStrictL(TTestResult& aResult); TInt MT_CSenIdentityProviderIdArray8_SetStrictL(TTestResult& aResult); void MT_CSenPolicy_NewLL(); void MT_CSenPolicy_NewLCL(); void MT_CSenPolicy_NewL_1L(); void MT_CSenPolicy_NewLC_1L(); void MT_CSenPolicy_SetIapIdLL(); void MT_CSenPolicy_IapIdL(); void MT_CSenPolicy_SetIdentityProviderIdsLL( TTestResult& aResult ); void MT_CSenPolicy_AddIdentityProviderIdLL( TTestResult& aResult ); void MT_CSenPolicy_RebuildFromL(); void MT_CSenPolicy_IdentityProviderIds8LL(); void MT_CSenPolicy_AcceptsL(); void MT_CSenProviderPolicy_NewLL(); void MT_CSenProviderPolicy_NewLCL(); void MT_CSenProviderPolicy_NewL_1L(); void MT_CSenProviderPolicy_NewLC_1L(); void MT_CSenProviderPolicy_AcceptsL(); void MT_CSenProviderPolicy_RebuildFromL(); TInt MT_CSenServicePattern_NewLL(TTestResult& aResult); TInt MT_CSenServicePattern_NewLCL(TTestResult& aResult); TInt MT_CSenServicePattern_NewL_1L(TTestResult& aResult); TInt MT_CSenServicePattern_NewLC_1L(TTestResult& aResult); TInt MT_CSenServicePattern_NewL_2L(TTestResult& aResult); TInt MT_CSenServicePattern_NewLC_2L(TTestResult& aResult); void MT_CSenServicePattern_ConsumerPolicyAsXmlLL(); void MT_CSenServicePattern_MatchesL(); // void MT_CSenServicePattern_StartElementLL();//need parsing some xml file TInt MT_CSenServicePattern_SetConsumerIapIdLL(TTestResult& aResult); TInt MT_CSenServicePattern_ConsumerIapIdL(TTestResult& aResult); TInt MT_CSenServicePattern_SetConsumerSnapIdLL(TTestResult& aResult); TInt MT_CSenServicePattern_ConsumerSnapIdL(TTestResult& aResult); TInt MT_CSenServicePattern_SetConsumerIdentityProviderIdsLL(TTestResult& aResult); TInt MT_CSenServicePattern_AddConsumerIdentityProviderIdLL(TTestResult& aResult); TInt MT_CSenServicePattern_ConsumerIdentityProviderIds8LL(TTestResult& aResult); TInt MT_CSenServicePattern_AcceptsConsumerPolicyL(TTestResult& aResult); TInt MT_CSenServicePattern_RebuildFromConsumerPolicyL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_NewLL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_NewLCL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_NewL_1L(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_NewLC_1L(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_NewL_2L(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_NewLC_2L(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_SetFrameworkIdLL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_NewElementNameL(TTestResult& aResult); // void MT_CSenXmlServiceDescription_CredentialsL();//need parsing some xml file TInt MT_CSenXmlServiceDescription_SetIapIdLL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_IapIdL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_SetSnapIdLL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_SnapIdL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_SetIdentityProviderIdsLL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_AddIdentityProviderIdLL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_RebuildFromL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_IdentityProviderIds8LL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_AcceptsL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_DescriptionClassTypeL(TTestResult& aResult); void MT_CSenXmlServiceDescription_MatchesL(); TInt MT_CSenXmlServiceDescription_ContractL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_HasFacetLL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_FacetValueL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_AddFacetLL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_SetFacetLL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_RemoveFacetL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_FacetsLL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_ScoreMatchLL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_EndpointL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_FrameworkIdL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_FrameworkVersionL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_SetContractLL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_SetEndPointLL(TTestResult& aResult); void MT_CSenXmlServiceDescription_AsXmlLL(); void MT_CSenXmlServiceDescription_AsXmlUnicodeLL(); void MT_CSenXmlServiceDescription_WriteAsXMLToLL(); TInt MT_CSenXmlServiceDescription_SetAttributesLL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_TransportPropertiesL(TTestResult& aResult); TInt MT_CSenXmlServiceDescription_SetTransportPropertiesL(TTestResult& aResult); // void MT_CSenXmlServiceDescription_ResumeParsingFromLL();//need parsing some xml file public: // Data // ?one_line_short_description_of_data //?data_declaration; protected: // Data // ?one_line_short_description_of_data //?data_declaration; private: // Data // Pointer to test (function) to be executed TestFunction iMethod; // Pointer to logger CStifLogger * iLog; RFileLogger logger; // ?one_line_short_description_of_data //?data_declaration; // Reserved pointer for future extension //TAny* iReserved; public: // Friend classes //?friend_class_declaration; protected: // Friend classes //?friend_class_declaration; private: // Friend classes //?friend_class_declaration; }; #endif // SENSERVDESCBCTEST_H // End of File
[ "none@none" ]
[ [ [ 1, 518 ] ] ]