IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C++ Discussion :

Erreur en créant un pointeur de vecteur


Sujet :

C++

  1. #1
    Membre averti
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    50
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Septembre 2006
    Messages : 50
    Par défaut Erreur en créant un pointeur de vecteur
    Bonjour à tous!

    Bon la je sais même pas exactement quels éléments présenter pour aider à la résolution du problème, un peu paumé le Tet2brick

    En gros j'ai une classe Application et dans la section private j'ai entre autre ceci:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    std::vector< std::vector< int > > *pathGrid;
    std::vector< Ogre::Vector3 > *movableObjects;
    Et je les initialise plus loin:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    pathGrid= new std::vector< std::vector< int > >(MAPSIZE,std::vector<int> (MAPSIZE,100000));
    movableObjects= new std::vector< Ogre::Vector3 >(0);


    Deux pointeurs vers des vecteurs que je vais utiliser dans toute la classe et que je vais envoyer à d'autres objets pour qu'ils puissent les manipuler.

    Mais lorsque je lance l'application elle plante en me retournant un "Access violation writing location... " (selon mes modifications que j'ai testées soit à l'initialisation, soit plus loin dans le code mais sans que je voie vraiment le rapport avec ces variables précises)

    Par contre si je retire le vecteur movableObjects, tout fonctionne parfaitement, comme si je ne pouvais pas créer un second pointeur vers un vecteur...

    Vous avez une idée?


    Merci d'avance

    Au cas ou la totalité du fichier main.cpp (je peux fournir les autres fichiers au besoin)
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
     
    #include <Ogre.h>
    #include <OIS/OIS.h>
    #include <CEGUI/CEGUI.h>
    #include <OgreCEGUIRenderer.h>
    #include <stdio.h>
    #include <fcntl.h>
    #include <io.h>
    #include <iostream>
    #include <string>
     
    #include "data.h"
     
    #include "Level.h"
    #include "KeyFrameListener.h"
     
    using namespace Ogre;
     
     
     
     
    class Application
    {
    public:
     
    	void go()
        {
     
    		pathGrid= new std::vector< std::vector< int > >(MAPSIZE,std::vector<int> (MAPSIZE,100000));
    		movableObjects= new std::vector< Ogre::Vector3 >(0);
     
    		createRoot();
            defineResources();
            setupRenderSystem();
            createRenderWindow();
            initializeResourceGroups();
            setupScene();
            setupInputSystem();
            setupCEGUI();
            createFrameListener();
            startRenderLoop();
        }
     
        ~Application()
        {
            mInputManager->destroyInputObject(mKeyboard);
            OIS::InputManager::destroyInputSystem(mInputManager);
    		delete mListener;
            delete mRoot;
        }
     
    private:
        Root *mRoot;
        OIS::Keyboard *mKeyboard;
    	OIS::Mouse *mMouse;
        OIS::InputManager *mInputManager;
        KeyFrameListener *mListener;
    	CEGUI::OgreCEGUIRenderer *mRenderer;
        CEGUI::System *mSystem;
    	Ogre::Vector3 *target;
    	std::vector< std::vector< int > > *pathGrid;
    	std::vector< Ogre::Vector3 > *movableObjects;
     
     
        void createRoot()
        {
            mRoot = new Root();
        }
     
        void defineResources()
        {
            String secName, typeName, archName;
            ConfigFile cf;
            cf.load("resources.cfg");
     
            ConfigFile::SectionIterator seci = cf.getSectionIterator();
            while (seci.hasMoreElements())
            {
                secName = seci.peekNextKey();
                ConfigFile::SettingsMultiMap *settings = seci.getNext();
                ConfigFile::SettingsMultiMap::iterator i;
                for (i = settings->begin(); i != settings->end(); ++i)
                {
                    typeName = i->first;
                    archName = i->second;
                    ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
                }
            }
        }
     
        void setupRenderSystem()
        {
            if (!mRoot->restoreConfig() && !mRoot->showConfigDialog())
                throw Exception(52, "User canceled the config dialog!", "Application::setupRenderSystem()");
     
            //// Do not add this to the application
            //RenderSystem *rs = mRoot->getRenderSystemByName("Direct3D9 Rendering Subsystem");
            //                                      // or use "OpenGL Rendering Subsystem"
            //mRoot->setRenderSystem(rs);
            //rs->setConfigOption("Full Screen", "No");
            //rs->setConfigOption("Video Mode", "800 x 600 @ 32-bit colour");
        }
     
        void createRenderWindow()
        {
            mRoot->initialise(true, "Tutorial Render Window");
     
            //// Do not add this to the application
            //mRoot->initialise(false);
            //HWND hWnd = 0;  // Get the hWnd of the application!
            //NameValuePairList misc;
            //misc["externalWindowHandle"] = StringConverter::toString((int)hWnd);
            //RenderWindow *win = mRoot->createRenderWindow("Main RenderWindow", 800, 600, false, &misc);
        }
     
        void initializeResourceGroups()
        {
            TextureManager::getSingleton().setDefaultNumMipmaps(5);
            ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
        }
     
        void setupScene()
        {
            /*SceneManager *mgr = mRoot->createSceneManager(ST_GENERIC, "Default_SceneManager");
            Camera *cam = mgr->createCamera("Camera");
            Viewport *vp = mRoot->getAutoCreatedWindow()->addViewport(cam);*/
     
    		//tableaux pour le pathfinding
    		/*std::vector <Ogre::Vector3 *> pathNodes(1,&Ogre::Vector3());
    		std::vector <bool> pathNodesWalkable(1,true);*/
     
    		//std::vector< std::vector< int > > pathGrid(256,std::vector<int> (256,100));
    		//std::vector<Ogre::String> movableObjects(1,"tmp");
    		//std::vector<Ogre::Entity *>	selectedObjects;
     
     
    		Level::Level(mRoot, pathGrid);
     
     
     
     
     
        }
     
        void setupInputSystem()
        {
            size_t windowHnd = 0;
            std::ostringstream windowHndStr;
            OIS::ParamList pl;
            RenderWindow *win = mRoot->getAutoCreatedWindow();
     
            win->getCustomAttribute("WINDOW", &windowHnd);
            windowHndStr << windowHnd;
            pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
            mInputManager = OIS::InputManager::createInputSystem(pl);
     
            try
            {
                mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject(OIS::OISKeyboard, true));
                mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject(OIS::OISMouse, true));
                //mJoy = static_cast<OIS::JoyStick*>(mInputManager->createInputObject(OIS::OISJoyStick, false));
            }
            catch (const OIS::Exception &e)
            {
                throw new Exception(42, e.eText, "Application::setupInputSystem");
            }
        }
     
        void setupCEGUI()
        {
            SceneManager *mgr = mRoot->getSceneManager("Default_SceneManager");
            RenderWindow *win = mRoot->getAutoCreatedWindow();
     
            // CEGUI setup
            mRenderer = new CEGUI::OgreCEGUIRenderer(win, Ogre::RENDER_QUEUE_OVERLAY, false, 3000, mgr);
            mSystem = new CEGUI::System(mRenderer);
     
            // Other CEGUI setup here.
     
    		CEGUI::SchemeManager::getSingleton().loadScheme((CEGUI::utf8*)"TaharezLookSkin.scheme");
            CEGUI::MouseCursor::getSingleton().setImage((CEGUI::utf8*)"TaharezLook", (CEGUI::utf8*)"MouseArrow");
     
     
     
     
        }
     
        void createFrameListener()
        {
            /*mListener = new ExitListener(mKeyboard);
            mRoot->addFrameListener(mListener);*/
     
     
     
    		mListener = new KeyFrameListener(mKeyboard, mMouse, mRoot, target, pathGrid);
            mRoot->addFrameListener(mListener);
        }
     
        void startRenderLoop()
        {
    		mRoot->startRendering();
     
            //// Do not add this to the application
            //while (mRoot->renderOneFrame())
            //{
            //    // Do some things here, like sleep for x milliseconds or perform other actions.
            //}
        }
    };
     
    #if OGRE_PLATFORM == PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WIN32
    #define WIN32_LEAN_AND_MEAN
    #include "windows.h"
     
    INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT)
    #else
    int main(int argc, char **argv)
    #endif
    {
        try
        {
            Application app;
            app.go();
        }
        catch(Exception& e)
        {
    #if OGRE_PLATFORM == PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WIN32
            MessageBoxA(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
    #else
            fprintf(stderr, "An exception has occurred: %s\n",
                e.getFullDescription().c_str());
    #endif
        }
     
        return 0;
    }

  2. #2
    Membre Expert

    Inscrit en
    Mai 2008
    Messages
    1 014
    Détails du profil
    Informations forums :
    Inscription : Mai 2008
    Messages : 1 014
    Par défaut
    Bonjour,
    Citation Envoyé par tet2brick Voir le message
    Vous avez une idée?
    Oui, peut être déjà essayer de remplacer :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    std::vector< std::vector< int > > *pathGrid;
    std::vector< Ogre::Vector3 > *movableObjects;
    par
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    std::vector< std::vector< int > > pathGrid;
    std::vector< Ogre::Vector3 > movableObjects;
    Car je soupçonne ton emploi d'un pointeur de n'être pas vraiment justifié. (surtout si tu débutes en C++, car pour une raison que je ne comprends pas bien, les débutants en C++ semblent adorer mettre plein de pointeurs partout )

    Pour ce qui est de :
    "Access violation writing location... "
    Généralement, il suffit de lancer le code avec un debuggeur pour qu'il indique la ligne qui provoque l'erreur.

    Edit : Au fait, pourquoi tu ne nous as pas donné le message d'erreur complet ?
    On peut souvent en tirer des infos, par exemple si c'est quelque chose comme "Access violation writing location 0x00000000" alors ça veut dire que tu essayes de déréférencer un pointeur nul.

  3. #3
    Membre averti
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    50
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Septembre 2006
    Messages : 50
    Par défaut
    Oui, peut être déjà essayer de remplacer :
    Code :

    std::vector< std::vector< int > > *pathGrid;
    std::vector< Ogre::Vector3 > *movableObjects;

    par
    Code :

    std::vector< std::vector< int > > pathGrid;
    std::vector< Ogre::Vector3 > movableObjects;

    Car je soupçonne ton emploi d'un pointeur de n'être pas vraiment justifié. (surtout si tu débutes en C++, car pour une raison que je ne comprends pas bien, les débutants en C++ semblent adorer mettre plein de pointeurs partout )
    Je débute effectivement
    Maintenant savoir si c'est justifié, je ne sais pas, j'ai utilisé un pointeur parce que j'ai besoin de modifier/ajouter/supprimer/lire des entrées de ce vecteur dans d'autres classes et je ne connais pas d'autre moyen qu'un pointeur pour y arriver.

    Actuellement ces classes sont créées comme ceci par exemple:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Level::Level(mRoot, pathGrid);
    Si je me passe de pointeur et que je créée la classe comme ceci:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Level::Level(mRoot, &pathGrid);
    ça plante, j'avais cru comprendre que si je ne créait pas un pointeur et ne lui allouait pas de mémoire, la variable avait une durée de vie limitée, donc il pouvait y avoir un plantage quand j'y faisait appel... mais de nouveau j'ai peut être mal compris

    Tandis que la précédente version fonctionne...
    (sauf quand j'ajoute *movableObjects, mais ça c'était par après)

    Généralement, il suffit de lancer le code avec un debuggeur pour qu'il indique la ligne qui provoque l'erreur.
    J'ai la ligne qui provoque l'erreur, mais je ne comprend pas pourquoi cette ligne en provoque une... (de nouveau une ligne qui fonctionnait parfaitement bien avant l'ajout de *movableObjects) C'est une ligne dans un autre fichier que celui que j'ai fournis.

    Au fait, pourquoi tu ne nous as pas donné le message d'erreur complet ?
    On peut souvent en tirer des infos, par exemple si c'est quelque chose comme "Access violation writing location 0x00000000" alors ça veut dire que tu essayes de déréférencer un pointeur nul.
    Désolé, je sais pas toujours quelles informations fournir et je me sens parfois un peu perdu ^^
    Voila l'erreur:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    First-chance exception at 0x00402c6a in OgrePathFinding.exe: 0xC0000005: Access violation writing location 0x00000000.
    Unhandled exception at 0x00402c6a in OgrePathFinding.exe: 0xC0000005: Access violation writing location 0x00000000.
    effectivement ça semble correspondre à ce que tu dis
    Mais j'ai aucune idée de comment régler ça

    Merci pour la réponse en tout cas

  4. #4
    Membre éprouvé
    Profil pro
    Directeur technique
    Inscrit en
    Juillet 2007
    Messages
    107
    Détails du profil
    Informations personnelles :
    Localisation : France, Maine et Loire (Pays de la Loire)

    Informations professionnelles :
    Activité : Directeur technique

    Informations forums :
    Inscription : Juillet 2007
    Messages : 107
    Par défaut
    D'après la doc : http://www.cplusplus.com/reference/stl/vector/vector/

    L'argument du constructeur a 1 paramètre est l'allocateur a utiliser,
    Tu lui passe un pointeur null a la place d'un allocateur mémoire

    Crée tes vectors sans paramètre pour tester

  5. #5
    Membre averti
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    50
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Septembre 2006
    Messages : 50
    Par défaut
    Citation Envoyé par Christuff Voir le message
    D'après la doc : http://www.cplusplus.com/reference/stl/vector/vector/

    L'argument du constructeur a 1 paramètre est l'allocateur a utiliser,
    Tu lui passe un pointeur null a la place d'un allocateur mémoire

    Crée tes vectors sans paramètre pour tester
    Désolé d'être lourd mais... en pratique ça donnerait quoi dans mon cas? parce que je suis pas sur de comprendre ce que tu veux dire

    Merci d'avance

  6. #6
    Membre éprouvé
    Profil pro
    Directeur technique
    Inscrit en
    Juillet 2007
    Messages
    107
    Détails du profil
    Informations personnelles :
    Localisation : France, Maine et Loire (Pays de la Loire)

    Informations professionnelles :
    Activité : Directeur technique

    Informations forums :
    Inscription : Juillet 2007
    Messages : 107
    Par défaut
    remplace

    pathGrid= new std::vector< std::vector< int > >(MAPSIZE,std::vector<int> (MAPSIZE,100000));
    movableObjects= new std::vector< Ogre::Vector3 >(0);
    par


    pathGrid= new std::vector< std::vector< int > >();
    movableObjects= new std::vector< Ogre::Vector3 >();
    Et remplis manuellement après (au moins pour le debug).

  7. #7
    Membre averti
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    50
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Septembre 2006
    Messages : 50
    Par défaut
    J'ai essayé, toujours la même erreur...

    ça se situe dans ce fichier si jamais, (mais vu la taille je comprendrais qu'on ne veuille pas fouiller dedans):
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    #include "KeyFrameListener.h"
    #include "data.h"
    #include <math.h>
    //#include "GameMenu.h"
     
     
    KeyFrameListener::KeyFrameListener(OIS::Keyboard *keyboard, OIS::Mouse *mouse, Ogre::Root *root, Ogre::Vector3 *target, std::vector< std::vector< int > > *pathGrid)
        {
            mRoot = root;
    		mKeyboard = keyboard;
    		mMouse = mouse;
            mContinue = true;
    		mKeyboard->setEventCallback(this);
    		mMouse->setEventCallback(this);
    		mTarget=target;
    		mWalkSpeed=300;
    		//mPaused=Paused;
    		//mMenu = menu;
    		mPathGrid=pathGrid;
    		mPathNodes.push_back(Ogre::Vector3(1250,0,550));
    		mPathGridNode=std::vector< std::vector< Ogre::Vector3 * > >(MAPSIZE,std::vector<Ogre::Vector3 *> (MAPSIZE,&(Ogre::Vector3(0,0,0))));
    		moving=false;
    		debugTest=true;
    		path=new std::vector< void* >(1);
    		isDebug=false;		
     
    		mRobotNode=mRoot->getSceneManager("Default_SceneManager")->getSceneNode("robotNode");		
     
    		// Create RaySceneQuery
    		mRaySceneQuery = mRoot->getSceneManager("Default_SceneManager")->createRayQuery(Ogre::Ray());
     
    		//parentNodePathGrid=mRoot->getSceneManager("Default_SceneManager")->getRootSceneNode()->createChildSceneNode("parentNodePathGrid");
     
    		dbFile = "pathdb.db3";
     
    		db.open(dbFile);
     
    		/*for(int x=0;x<MAPSIZE;x++)
    		{
    			for(int z=0;z<MAPSIZE;z++)
    			{
    				Ogre::Vector3 *tmpVector=new Ogre::Vector3(x,0,z);
    				mPathGridNode[x][z]=tmpVector;
    			}
    		}*/
     
     
     
        }
     
        bool KeyFrameListener::frameStarted(const Ogre::FrameEvent &evt)
        {
     
    		mKeyboard->capture();
    		mMouse->capture();
     
    		nextMove(evt);
     
    		/*if(mPaused->GetGameState())
    		{
    			return mMenu->getQuitStatus();
    		}
    		else
    		{
    			return true;
    		}*/
     
     
     
    		/*for(int i=0;i<256;i++)
    		{
    			for(int j=0;j<256;j++)
    			{
     
    				if((*mPathGrid)[i][j]<100)
    				{
    					Ogre::Entity *archiEntity=mRoot->getSceneManager("Default_SceneManager")->getEntity("pathBoxe_"+Ogre::StringConverter::toString(i)+"_"+Ogre::StringConverter::toString(j));
    					archiEntity->setMaterialName("TestNico/transparentGreen");
    					archiEntity->setVisible(true);
    				}
     
     
    				if((*mPathGrid)[i][j]<100)
    				{
    					Ogre::Entity *archiEntity=mRoot->getSceneManager("Default_SceneManager")->getEntity("pathBoxe_"+Ogre::StringConverter::toString(i)+"_"+Ogre::StringConverter::toString(j));
    					archiEntity->setMaterialName("TestNico/transparentGreen");
    					archiEntity->setVisible(true);
    				}
    				else
    				{
    					archiEntity->setMaterialName("TestNico/transparentRed");
    					archiEntity->setVisible(false);
    				}				
     
    			}
    		}*/
     
     
     
    		if(mContinue)
    		{
    			return true;
    		}
    		else
    		{
    			return false;
    		}
     
     
     
        }
     
    	//mouse listener
    	bool KeyFrameListener::mouseMoved(const OIS::MouseEvent &arg)
    	{
    		/*if(mPaused->GetGameState())
    		{
    			mMenu->SetMousePos(arg.state.X.rel, arg.state.Y.rel);
    		}
    		else
    		{
    			int mRotateSpeed=1;
    			Ogre::Camera *mCamera=mRoot->getSceneManager("Default_SceneManager")->getCamera("CameraOne");
    			mCamera->yaw(Ogre::Degree(-arg.state.X.rel * mRotateSpeed));
    			mCamera->pitch(Ogre::Degree(-arg.state.Y.rel * mRotateSpeed));
    		}*/
    		//std::cout << "mouved!!" << std::endl;
    			/*int mRotateSpeed=1;
    			Ogre::Camera *mCamera=mRoot->getSceneManager("Default_SceneManager")->getCamera("CameraOne");
    			mCamera->yaw(Ogre::Degree(-arg.state.X.rel * mRotateSpeed));
    			mCamera->pitch(Ogre::Degree(-arg.state.Y.rel * mRotateSpeed));*/
    		CEGUI::System::getSingleton().injectMouseMove(arg.state.X.rel, arg.state.Y.rel);
    		return true;
    	}
     
    	bool KeyFrameListener::mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id)
    	{
    		/*if(mPaused->GetGameState())
    		{
    			mMenu->mousePressed(id);
    		}*/
    		return true;
    	}
     
    	bool KeyFrameListener::mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id)
    	{
    		/*if(mPaused->GetGameState())
    		{
    			mMenu->mouseReleased(id);
    		}*/
     
    		 arg.state.width=mRoot->getAutoCreatedWindow()->getWidth();
    		 arg.state.height=mRoot->getAutoCreatedWindow()->getHeight();
    		  Ogre::Camera *mCamera=mRoot->getSceneManager("Default_SceneManager")->getCamera("CameraOne");
     
     
    		 if (id == OIS::MB_Left)
           {
    			// Setup the ray scene query, use CEGUI's mouse position
               CEGUI::Point mousePos = CEGUI::MouseCursor::getSingleton().getPosition();
    		   Ogre::Ray mouseRay = mCamera->getCameraToViewportRay(mousePos.d_x/float(arg.state.width), mousePos.d_y/float(arg.state.height));
               mRaySceneQuery->setRay(mouseRay);
    		   mRaySceneQuery->setSortByDistance(true);
    		   //mRaySceneQuery->setQueryMask(GROUND_MASK);
     
    		  //std::cout << mouseRay.getPoint(mCamera->getPosition().y) << std::endl;
     
    		   //std::cout << mouseRay.getOrigin() << std::endl;
     
     
     
     
    		   // Execute query
    		   Ogre::RaySceneQueryResult &result = mRaySceneQuery->execute();
    		   Ogre::RaySceneQueryResult::iterator itr = result.begin( );
     
     
    		   //std::cout <<  result.size() << std::endl;
     
     
               // Get results, put it in red/green
    		   for (itr = result.begin(); itr != result.end(); itr++)
    		   {
                   //std::cout << "touch1!"  << std::endl;
    			   if (itr->worldFragment)
                   {
    				   if(isDebug)
    				   {
    					   targetX=floor(itr->worldFragment->singleIntersection.x/TILESIZE);
    					   targetZ=floor(itr->worldFragment->singleIntersection.z/TILESIZE);
    					   //std::cout <<  targetX << " " <<  targetZ  << std::endl;
    					   if((*mPathGrid)[targetX][targetZ]<100000)
    					   {
    							(*mPathGrid)[targetX][targetZ]=100000;
    							mRoot->getSceneManager("Default_SceneManager")->destroyEntity("pathBoxe_"+Ogre::StringConverter::toString(targetX)+"_"+Ogre::StringConverter::toString(targetZ));
    							mRoot->getSceneManager("Default_SceneManager")->destroySceneNode("pathBoxeNode_"+Ogre::StringConverter::toString(targetX)+"_"+Ogre::StringConverter::toString(targetZ));			
     
     
    							sqlQuery.str("");
    							sqlQuery << "delete from PathGrid where posX=" << targetX << " and posZ=" << targetZ;
     
    							try
    							{
    								query = db.execQuery(sqlQuery.str().c_str());
    							}
    							catch (CppSQLite3Exception& e)
    							{
    								std::cout << "test sql code keyframe delete " << e.errorCode() <<  std::endl;
    								std::cout << sqlQuery.str() << std::endl;
    								std::cout << "erreur:  " << e.errorMessage() << std::endl;
    							}
     
     
     
     
    					   }
    					   else
    					   {
    				     		(*mPathGrid)[targetX][targetZ]=1;
     
    							Ogre::Vector3 size = Ogre::Vector3( TILESIZE, 10, TILESIZE );
    							Ogre::SceneNode *pathBoxeNode;
    							Ogre::Entity *pathBoxeEntity;
     
    							pathBoxeNode = mRoot->getSceneManager("Default_SceneManager")->getRootSceneNode()->createChildSceneNode("pathBoxeNode_"+Ogre::StringConverter::toString(targetX)+"_"+Ogre::StringConverter::toString(targetZ));
     
    							pathBoxeEntity = mRoot->getSceneManager("Default_SceneManager")->createEntity("pathBoxe_"+Ogre::StringConverter::toString(targetX)+"_"+Ogre::StringConverter::toString(targetZ), "box.mesh" );
     
    							pathBoxeNode->attachObject( pathBoxeEntity );
     
    							pathBoxeNode->setScale( size );
     
    							float posNodeX=targetX*TILESIZE+TILESIZE/2;
    							float posNodeZ=targetZ*TILESIZE+TILESIZE/2;
     
    							pathBoxeNode->setPosition(posNodeX,0,posNodeZ);
    							pathBoxeEntity->setMaterialName("TestNico/transparentGreen");
     
    							sqlQuery.str("");
    							sqlQuery << "insert into PathGrid (posX,posZ, moveCost) values(" << targetX << "," << targetZ << ",1)";
     
    							try
    							{
    								query = db.execQuery(sqlQuery.str().c_str());
    							}
    							catch (CppSQLite3Exception& e)
    							{
    								std::cout << "test sql code keyframe insert " << e.errorCode() <<  std::endl;
    								std::cout << sqlQuery.str() << std::endl;
    								std::cout << "erreur:  " << e.errorMessage() << std::endl;
    							}
     
     
    					   }
    				   }
     
    			   }
     
    		   }
     
    		}
     
    		if (id == OIS::MB_Right)
           {
     
     
    		   Ogre::SceneNode *targetNode=mRoot->getSceneManager("Default_SceneManager")->getSceneNode("cylinderNode");
     
     
    		   // Setup the ray scene query, use CEGUI's mouse position
               CEGUI::Point mousePos = CEGUI::MouseCursor::getSingleton().getPosition();
    		   Ogre::Ray mouseRay = mCamera->getCameraToViewportRay(mousePos.d_x/float(arg.state.width), mousePos.d_y/float(arg.state.height));
               mRaySceneQuery->setRay(mouseRay);
    		   mRaySceneQuery->setSortByDistance(true);
    		   //mRaySceneQuery->setQueryMask(GROUND_MASK);
     
    		  //std::cout << mouseRay.getPoint(mCamera->getPosition().y) << std::endl;
     
    		   //std::cout << mouseRay.getOrigin() << std::endl;
     
     
     
     
    		   // Execute query
    		   Ogre::RaySceneQueryResult &result = mRaySceneQuery->execute();
    		   Ogre::RaySceneQueryResult::iterator itr = result.begin( );
     
     
    		   //std::cout <<  result.size() << std::endl;
     
               // Get results, create move the target node to the position
    		   for (itr = result.begin(); itr != result.end(); itr++)
    		   {
                   //std::cout << "touch1!"  << std::endl;
    			   if (itr->worldFragment)
                   {
    				   //std::cout << "touch2!"  << std::endl;
    				   targetNode->setPosition(itr->worldFragment->singleIntersection);
    				   *mTarget=Ogre::Vector3(targetNode->getPosition().x,1,targetNode->getPosition().z);
    				   //std::cout << *mTarget  << std::endl;
     
    				   float endX=targetNode->getPosition().x;
    				   float endZ=targetNode->getPosition().z;
    				   float startX=mRoot->getSceneManager("Default_SceneManager")->getSceneNode("robotNode")->getPosition().x;
    				   float startZ=mRoot->getSceneManager("Default_SceneManager")->getSceneNode("robotNode")->getPosition().z;
    				   int gridStartX=floor(double(startX)/TILESIZE);
    				   int gridStartZ=floor(double(startZ)/TILESIZE);
    				   int gridEndX=floor(double(endX)/TILESIZE);
    				   int gridEndZ=floor(double(endZ)/TILESIZE);
    				   if((*mPathGrid)[gridEndX][gridEndZ]<100000)
    				   {
    					//mPathNodes=aStarCalcul(startX,startZ,endX,endZ);
    				    MicroPather pather( this );
     
    					//std::vector< void* > path;
    					float totalCost;
     
     
     
    					/*Ogre::String startState=(Ogre::StringConverter::toString(gridStartX)+","+Ogre::StringConverter::toString(gridStartZ));
    					Ogre::String endState=(Ogre::StringConverter::toString(gridEndX)+","+Ogre::StringConverter::toString(gridEndZ));*/
    					//std::cout << "test 1 " << startState << std::endl;
     
    					int result = pather.Solve(XYToNode( gridStartX, gridStartZ ), XYToNode( gridEndX, gridEndZ ), path, &totalCost );
    					//std::cout << "totalcost: " << totalCost << std::endl;
     
    					for(int i=0;i<path->size();i++)
    					{
    						int x, y;
    						NodeToXY( (*path)[i], &x, &y );
    						Ogre::Entity *entityTmp=mRoot->getSceneManager("Default_SceneManager")->getEntity("pathBoxe_"+Ogre::StringConverter::toString(x)+"_"+Ogre::StringConverter::toString(y));
    						entityTmp->setMaterialName("TestNico/transparentBlue");
    						std::cout << x << "," << y << std::endl;
    					}
     
    					moving=true;
    				   }
    			   }
    			   /*if(itr->movable)
    			   {
    				   std::cout << itr->movable->getName() << std::endl;
    			   }*/
    		   }
     
     
     
     
     
    		  mDestination=0;
     
    		  //std::cout << mPathNodes[mDestination] << " " << mPathNodes.size()  << std::endl;
     
     
     
     
     
     
           }
     
    		return true;
    	}
     
    	// KeyListener
    	bool KeyFrameListener::keyPressed(const OIS::KeyEvent &e)
        {
    		//Ogre::LogManager::getSingleton().logMessage("tagada: "+Ogre::StringConverter::toString(e.key));
     
    		switch (e.key)
            {
            case OIS::KC_ESCAPE: 
                mContinue = false;
    			//mPaused->SetGameState(!mPaused->GetGameState());
    			//mMenu->setVisible(mPaused->GetGameState());
                break;
    		case OIS::KC_TAB:
                isDebug=!isDebug;
    			std::cout << "Debug mode: " << isDebug << std::endl;
    			//mPaused->SetGameState(!mPaused->GetGameState());
    			//mMenu->setVisible(mPaused->GetGameState());
                break;
     
            }
            return true;
        }
     
     
    	bool KeyFrameListener::keyReleased( const OIS::KeyEvent &e )
    	{
    		//Ogre::LogManager::getSingleton().logMessage("tagada: "+Ogre::StringConverter::toString(e.key));
     
    		switch (e.key)
            {
            case OIS::KC_P: 
    			//mPaused->SetGameState(!mPaused->GetGameState());
                break;
     
     
     
            }
     
    		return true;
    	}
     
    	bool KeyFrameListener::nextMove(const Ogre::FrameEvent &evt)
    	{
    		Ogre::Entity *robotEntity=mRoot->getSceneManager("Default_SceneManager")->getEntity("Robot");
    		if(moving)
    		{
     
     
    			int x,y;
    			NodeToXY( (*path)[mDestination], &x, &y );
     
    			mDirection=Ogre::Vector3(x*TILESIZE,0,y*TILESIZE)-robotEntity->getParentNode()->getPosition();
    			mDistance=mDirection.normalise();
     
    			Ogre::Real move = mWalkSpeed * evt.timeSinceLastFrame;
     
     
     
    			if(mDistance-move<=0)
    			{
    				mDestination++;
    			}
     
    			//std::cout << mDestination << std::endl;
     
    			//std::cout << robotEntity->getParentNode()->getPosition() << std::endl;
     
    				//std::cout << robotEntity->getParentNode()->getPosition() << " = " <<   mDirection << " * " << move << " = " << mDirection * move  << std::endl;
     
    			Ogre::Vector3 mMoveFinal=mDirection * move;
    			/*if(robotEntity->getParentNode()->getPosition().z<0)
    			{
    				std::cout << robotEntity->getParentNode()->getPosition() << " = " <<   mDirection << " * " << move << " = " << mDirection * move  << std::endl;
    			}*/
     
    			if(mDestination<path->size())
    			{
    				mAnimationState = robotEntity->getAnimationState( "Walk" );
    				mAnimationState->setLoop( true );
    				mAnimationState->setEnabled( true );
    				robotEntity->getParentSceneNode()->translate( mDirection * move );	
    				//mNpcBody->setPositionOrientation(mFinalDest,mEntity->getParentSceneNode()->getOrientation());
    				//Ogre::LogManager::getSingleton().logMessage("mFinalDest : "+Ogre::StringConverter::toString(mFinalDest));
    				//mNpcBody->addForce(Ogre::Vector3(0,10000,0));
    				//mNpcBody->setVelocity(
     
     
    			}
    			else
    			{
     
    				mAnimationState = robotEntity->getAnimationState( "Idle" );
    				mAnimationState->setLoop( true );
    				mAnimationState->setEnabled( true );
    				moving=false;
     
    			}
     
     
    		}
    		else
    		{
    			mAnimationState = robotEntity->getAnimationState( "Idle" );
    			mAnimationState->setLoop( true );
    			mAnimationState->setEnabled( true );
    		}
     
    		Ogre::Vector3 src = robotEntity->getParentSceneNode()->getOrientation( ) * Ogre::Vector3::UNIT_X;
    		if ( (1.0f + src.dotProduct( mDirection )) < 0.0001f ) 
    		{
    			robotEntity->getParentSceneNode()->yaw( Ogre::Degree(180) );
    		}
    		else
    		{
    			Ogre::Quaternion quat = src.getRotationTo(Ogre::Vector3(mDirection.x,0,mDirection.z));
    			robotEntity->getParentSceneNode()->rotate( quat );
    		} // else
     
     
    		mAnimationState->addTime(evt.timeSinceLastFrame);
     
    		return true;
    	}
     
    float KeyFrameListener::calculDistanceH(int startX,int startZ,int endX,int endZ)
    {
    	return sqrt(pow(double(endX-(startX)),2)+pow(double(endZ-(startZ)),2));
    }
     
    float KeyFrameListener::calculDistanceG(int xCounter,int zCounter,std::vector< std::vector< int > > tileParentX,std::vector< std::vector< int > > tileParentZ)
    {
    	int totalCounter=0;
    	while(xCounter!=-1)
    	{
     
    		float xCounterTmp=tileParentX[xCounter][zCounter];
    		float zCounterTmp=tileParentZ[xCounter][zCounter];
    		xCounter=xCounterTmp;
    		zCounter=zCounterTmp;
    		totalCounter++;
     
    	}
     
    	return totalCounter;
    }
     
    std::vector <Ogre::Vector3> KeyFrameListener::aStarCalcul(int startX,int startZ,int endX,int endZ)
    {
     
     
    	//test à retirer!!!!!!!!!!!!!!!
    	mPathNodes.clear();
     
    	return mPathNodes;
     
     
     
    }
     
    float KeyFrameListener::LeastCostEstimate( void* nodeStart, void* nodeEnd ) 
    {
     
    	int xStart, yStart, xEnd, yEnd;
    		NodeToXY( nodeStart, &xStart, &yStart );
    		NodeToXY( nodeEnd, &xEnd, &yEnd );
     
    		/* Compute the minimum path cost using distance measurement. It is possible
    		   to compute the exact minimum path using the fact that you can move only 
    		   on a straight line or on a diagonal, and this will yield a better result.
    		*/
    		int dx = xStart - xEnd;
    		int dy = yStart - yEnd;
    		return (float) sqrt( (double)(dx*dx) + (double)(dy*dy) );
    }
     
    void KeyFrameListener::AdjacentCost( void* node, std::vector< StateCost > *neighbors ) 
    {
     
    	int x, y;
    		const int dx[8] = { 1, 1, 0, -1, -1, -1, 0, 1 };
    		const int dy[8] = { 0, 1, 1, 1, 0, -1, -1, -1 };
    		const float cost[8] = { 1.0f, 1.41f, 1.0f, 1.41f, 1.0f, 1.41f, 1.0f, 1.41f };
     
     
     
    		NodeToXY( node, &x, &y );
     
    		for( int i=0; i<8; ++i ) {
    			int nx = x + dx[i];
    			int ny = y + dy[i];
     
    			int pass = Passable( nx, ny );
    			if ( pass > 0 ) {
     
    					// Normal floor
    					StateCost nodeCost = { XYToNode( nx, ny ), cost[i] };
    					neighbors->push_back( nodeCost );
     
    			}
    		}
     
    }
     
    void KeyFrameListener::PrintStateInfo( void* node ) 
    {
     
    }
     
    void KeyFrameListener::NodeToXY( void* node, int* x, int* y ) 
    {
    	int index = (int)node;
    	*y = index / MAPX;
    	*x = index - *y * MAPX;
    }
     
    void* KeyFrameListener::XYToNode( int x, int y )
    {
    	return (void*) ( y*MAPX + x );
    }
     
    int KeyFrameListener::Passable( int nx, int ny ) 
    {
    	if((*mPathGrid)[nx][ny]<100000)
    	{
    		return 1;
    	}
    	return 0;
    }
    à cette ligne ci:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    float endX=targetNode->getPosition().x;
    Donc je ne comprend pas trop en quoi ça entre en conflit avec le vecteur movableObjects... mais ça doit être le cas d'une manière ou d'une autre, parce que si je le retire, tout fonctionne parfaitement...

  8. #8
    Membre averti
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    50
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Septembre 2006
    Messages : 50
    Par défaut
    Youhou!

    On m'a un peu (tu parles... beaucoup aidé) et j'ai finalement trouvé, une variable qui n'était pas initialisée, ça fonctionnait bien avant, mais je suppose que l'ajout d'un vecteur à du mordre sur son adresse mémoire...

    Enfin ça marche maintenant, donc c'est nickel

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Erreur de manipulation de pointeur
    Par Bleys dans le forum Langage
    Réponses: 0
    Dernier message: 05/08/2008, 09h24
  2. Réponses: 2
    Dernier message: 06/05/2008, 15h18
  3. Erreurs de compilation des pointeurs
    Par hanry dans le forum Débuter
    Réponses: 7
    Dernier message: 18/03/2008, 14h34
  4. erreur dans programme java sur des vecteurs 3D
    Par HighSchool2005 dans le forum Langage
    Réponses: 18
    Dernier message: 15/02/2007, 16h38
  5. erreur 2397 : problème de pointeurs
    Par klair dans le forum Delphi
    Réponses: 5
    Dernier message: 29/05/2006, 11h55

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo