using NewtonCreateHeightFieldCollision

A place to discuss everything related to Newton Dynamics.

Moderators: Sascha Willems, walaber

Re: using NewtonCreateHeightFieldCollision

Postby noals » Tue Oct 02, 2012 10:40 am

i knew it ! i searched a little in the source but didnt know where the fonction was so i gave up.
If you use Visual C, you can detedt such cases by right clicking on the function name and chose "Go To Definition".

thx, i didnt know that.

i will post my code again later if it work or not.
noals
 
Posts: 32
Joined: Mon Sep 03, 2012 7:59 am

Re: using NewtonCreateHeightFieldCollision

Postby noals » Tue Oct 02, 2012 9:35 pm

ok here all the code i write to use newton and of course it crash miserably lol.

Code: Select all
#include <irrlicht.h>
#include <Newton.h>
#include "EasyBMP.h"

BMP heightmap; //bmp image
u32 heightmapX;
u32 heightmapY;

float* heightmapData = new float [256*256]; // allocate memory at runtime

int main()
{
   //init newton
   NewtonWorld*nWorld=NewtonCreate();

   //load the heightmap
   heightmap.ReadFromFile("heightmap/F18.bmp");
   //heightmapData
   for(heightmapX=0;heightmapX<heightmap.TellHeight();heightmapX++)
   {
      for(heightmapY=0;heightmapY<heightmap.TellWidth();heightmapY++)
      {
         RGBApixel pixelTemp = heightmap.GetPixel(heightmapX,heightmapY);
         heightmapData [heightmapX + heightmapY*256] = pixelTemp.Red*256;
      }
   }

   //Newton
   NewtonCollision* nTerrainCol = NewtonCreateHeightFieldCollision(
      nWorld,         //world pointer
      256,         //width
      256,            //height
      0,            //diagonal cut
      heightmapData,      //unsigned short* elevationMap - the actual elevation map as 16-bit integer array from ram
      0,
      400.0f,         //calcul one cell, check irrlicht scaling
      33.0f);         //maximum height
   NewtonBody* nTerrain=NewtonCreateDynamicBody(nWorld, nTerrainCol,0);
   NewtonDestroyCollision(nTerrainCol);

   while(device->run())
   if(device->isWindowActive())
   {
   }

   NewtonDestroy(nWorld);
}


easyBMP work pretty fine, i verified a random heightmapData[x,y] value with a little debug windows. (w/o using newton)
anyway, so the whole code compile fine, my 'device' open so i can choose the driver i want for rendering and then it crash.
it put my loop in the code to show that i dont put anything in it yet for newton.

do you see a problem in my code that could make it crash ?
i think newton need other fonction to work properly, right ? or just this code shouldnt crash my app ?
can you tell me the others fonctions needed to get newton to work ?
noals
 
Posts: 32
Joined: Mon Sep 03, 2012 7:59 am

Re: using NewtonCreateHeightFieldCollision

Postby noals » Sun Oct 07, 2012 1:40 am

here is my whole main.cpp
Code: Select all
#include <irrlicht.h>
#include <Newton.h>
#include "EasyBMP.h"
#include "driverChoice.h"

using namespace irr;

#ifdef _MSC_VER
#pragma comment(lib, "Irrlicht.lib")
#endif

///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////                       //////////////////////////////////////////////////////
//////////////////////////////      DEFINITION       //////////////////////////////////////////////////////
//////////////////////////////                       //////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////
bool keys[KEY_KEY_CODES_COUNT];
core::position2d<f32> cursor;            //mouse position
core::position2d<f32> screenCenter;         //screen center
f32 rotationSpeed=0.4;                  //player rotation speed.
f32 playerSpeed=5.5;                  //player speed
f32 cameraDistance;
f32 PI=3.1415926;
core::vector3df playerRot;
core::vector3df playerPos;
core::vector3df camTargetPos;
core::vector3df camTargetRot;
core::vector3df cameraPos;

BMP heightmap; //bmp image
u32 heightmapX;
u32 heightmapY;

float* heightmapData = new float [256*256]; // allocate memory at runtime

///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////                       //////////////////////////////////////////////////////
//////////////////////////////     EVENT RECEIVER    //////////////////////////////////////////////////////
//////////////////////////////                       //////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////
class myEventReceiver: public IEventReceiver
{
   public: virtual bool OnEvent(const SEvent& event)
   {
      switch(event.EventType)
      {
      case EET_MOUSE_INPUT_EVENT:
         switch(event.MouseInput.Event)
         {
            case EMIE_MOUSE_MOVED:
               cursor.X=event.MouseInput.X;
               cursor.Y=event.MouseInput.Y;
               return true;
            case EMIE_MOUSE_WHEEL:
               cameraDistance += event.MouseInput.Wheel/10;
               return true;
            default :
               return false;
         }
      case EET_KEY_INPUT_EVENT:
         keys[event.KeyInput.Key]=event.KeyInput.PressedDown;
         return true;
      default :
         return false;
      }
   }
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////                       //////////////////////////////////////////////////////
//////////////////////////////         MAIN          //////////////////////////////////////////////////////
//////////////////////////////                       //////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
   video::E_DRIVER_TYPE driverType=driverChoiceConsole();
   if(driverType==video::EDT_COUNT)
   return 1;

   SIrrlichtCreationParameters params;
   params.DriverType=driverType;
   params.WindowSize=core::dimension2d<u32>(800,600);
   IrrlichtDevice*device=createDeviceEx(params);

   if(device==0)
   return 1;

   video::IVideoDriver*driver=device->getVideoDriver();
   scene::ISceneManager*smgr=device->getSceneManager();
   gui::IGUIEnvironment*env=device->getGUIEnvironment();
   driver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT,true);
   gui::ICursorControl*myCursor=device->getCursorControl();
   device->getCursorControl()->setVisible(false);

   //init newton
   NewtonWorld*nWorld=NewtonCreate();
   
   //create event receiver
   myEventReceiver receiver;
   device->setEventReceiver(&receiver);
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////                       //////////////////////////////////////////////////////
//////////////////////////////        TERRAIN        //////////////////////////////////////////////////////
//////////////////////////////                       //////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////
   scene::ITerrainSceneNode*terrain=smgr->addTerrainSceneNode(
      "heightmap/F18.bmp",      //heightmap
      0,                     //parent node
      -1,                     //node id
      core::vector3df(0.0f,0.0f,0.0f),   //position
      core::vector3df(0.0f,0.0f,0.0f),   //rotation
      core::vector3df(400.0f,33.0f,300.0f),   //scale  256x400=102400 256x300=76800 height to define 400 33 300
      video::SColor(255,255,255,255),      //vertex color
      5,                     //maxLOD
      scene::ETPS_17,            //patch size
      3);                     //smooth factor
   terrain->setMaterialTexture(0,driver->getTexture("texture/herbe.jpg"));
   terrain->scaleTexture(1024,768);  //1024,
   terrain->setMaterialFlag(video::EMF_LIGHTING,false);

   //skybox
   scene::ISceneNode*skybox=smgr->addSkyBoxSceneNode(
      driver->getTexture("skybox/siege_up.jpg"),
      driver->getTexture("skybox/siege_dn.jpg"),
      driver->getTexture("skybox/siege_lf.jpg"),
      driver->getTexture("skybox/siege_rt.jpg"),
      driver->getTexture("skybox/siege_bk.jpg"),
      driver->getTexture("skybox/siege_ft.jpg"));

   //load the heightmap
   heightmap.ReadFromFile("heightmap/F18.bmp");
   //heightmapData
   for(heightmapX=0;heightmapX<heightmap.TellHeight();heightmapX++)
   {
      for(heightmapY=0;heightmapY<heightmap.TellWidth();heightmapY++)
      {
         RGBApixel pixelTemp = heightmap.GetPixel(heightmapX,heightmapY);
         heightmapData [heightmapX + heightmapY*256] = pixelTemp.Red*256;
      }
   }

   //Newton
   NewtonCollision* nTerrainCol = NewtonCreateHeightFieldCollision(
      nWorld,         //world pointer
      256,         //width
      256,            //height
      0,            //diagonal cut
      heightmapData,      //unsigned short* elevationMap - the actual elevation map as 16-bit integer array from ram
      0,
      400.0f,         //calcul one cell, check irrlicht scaling
      33.0f);         //maximum height
   NewtonBody* nTerrain=NewtonCreateDynamicBody(nWorld, nTerrainCol,0);
   NewtonDestroyCollision(nTerrainCol);
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
//////////////////////////////          PLAYER         ////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////
   scene::IAnimatedMeshSceneNode*playerNode=
      smgr->addAnimatedMeshSceneNode(smgr->getMesh("model/ninja.b3d"));
      playerNode->setMaterialTexture(0,driver->getTexture("model/ninja.bmp"));
      playerNode->setPosition(core::vector3df(64000.0f,0.0f,64000.0f)); //texturesale/2
      playerNode->setFrameLoop(206,250);
      playerNode->setAnimationSpeed(15);
      playerNode->setScale(core::vector3df(4.0f,4.0f,4.0f));
      playerNode->setMaterialFlag(video::EMF_LIGHTING,false);

   //camera target
   scene::ISceneNode*camTarget=
      smgr->addEmptySceneNode(0,-1);
      camTarget->setPosition(playerNode->getPosition());
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
//////////////////////////////        COLLISION        ////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
//////////////////////////////        ANIMATION        ////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
//////////////////////////////          CAMERA         ////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////
   scene::ICameraSceneNode*camera=
      smgr->addCameraSceneNode(
         camTarget,                           //parent
         core::vector3df(0.0f,0.0f,-(150.0f)),      //angleX,heigtY,distaneZ
         camTarget->getPosition(),               //target
         -1);                                 //id
   camera->setFarValue(80000.0f);

///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
//////////////////////////////           GUI           ////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////
      gui::IGUIStaticText*debug_panel=
      env->addStaticText(L"",core::rect<s32>(
      15,//gauche
      555,//haut
      200,//droite
      585),//bas
      true,true,0,-1,false); //100 : L - h
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
//////////////////////////////          LOOP           ////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////
   int lastFPS = -1;//fps for debug
   while(device->run())
   if(device->isWindowActive())
   {
      driver->beginScene(true, true, 0);
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
//////////////////////////////        CONTROLE         ////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////
      
      screenCenter.X=400;
      screenCenter.Y=300;
      
      camTargetRot.X=camTarget->getRotation().X+rotationSpeed*(screenCenter.Y-cursor.Y);      //rot vertical
      if(camTargetRot.X>89)camTargetRot.X=89;
      if(camTargetRot.X<1)camTargetRot.X=1;
      camTargetRot.Y=camTarget->getRotation().Y+rotationSpeed*(screenCenter.X-cursor.X)*-1;   //rot horizontal
      camTargetRot.Z=camTarget->getRotation().Z;

      playerRot.X=0;
      playerRot.Y=camTargetRot.Y;
      playerRot.Z=0;

      //cameraPos.X=camera->getPosition().X;
      //cameraPos.Y=camera->getPosition().Y;
      cameraPos.Z=camera->getPosition().Z+cameraDistance;

      playerPos=playerNode->getPosition();

      if(keys[KEY_KEY_Z]) //moving foward
      {
         f32 roty_rad=playerRot.Y*PI/180; //convert to radian
         playerPos.Z += playerSpeed*cos(roty_rad);
         playerPos.X += playerSpeed*sin(roty_rad);
      }
      if(keys[KEY_KEY_S]) //moving back
      {
         f32 roty_rad=playerRot.Y*PI/180;
         playerPos.Z -= playerSpeed*cos(roty_rad);
         playerPos.X -= playerSpeed*sin(roty_rad);
      }
      if(keys[KEY_KEY_Q]) //straing left
      {
         f32 roty_rad=playerRot.Y;
         roty_rad -= 90;
         roty_rad *= PI/180;
         playerPos.Z += playerSpeed*cos(roty_rad);
         playerPos.X += playerSpeed*sin(roty_rad);
      }
      if(keys[KEY_KEY_D]) //straing right
      {
         f32 roty_rad=playerRot.Y;
         roty_rad += 90;
         roty_rad *= PI/180;
         playerPos.Z += playerSpeed*cos(roty_rad);
         playerPos.X += playerSpeed*sin(roty_rad);
      }
      if(keys[KEY_KEY_E])playerPos.Y=playerPos.Y+2.0f*playerSpeed;
      if(keys[KEY_KEY_A])playerPos.Y=playerPos.Y-2.0f*playerSpeed;


      camera->setTarget(camTarget->getPosition());
      camera->setPosition(cameraPos);
      playerNode->setPosition(playerPos);
      playerNode->setRotation(playerRot);
      camTarget->setPosition(playerPos);
      camTarget->setRotation(camTargetRot);
      
      myCursor->setPosition(400,300);
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
//////////////////////////////           DEBUG         ////////////////////////////////////////////////////
//////////////////////////////                         ////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////
      
      
      core::stringw debug1 = L"";
         debug1+="EasyBMP test = ";
         debug1+=heightmapData [20 + 20*256];
         debug1+="\n";
      debug_panel->setText(debug1.c_str());
        debug_panel->setOverrideColor(video::SColor(255,255,255,255));
        debug_panel->setBackgroundColor(video::SColor(255,0,0,0));
      
      int fps = driver->getFPS();
      if (lastFPS != fps)
      {core::stringw debugfps=L"";debugfps+=fps;lastFPS=fps;}
      core::stringw debug2 = L"FPS= ";
         debug2+=fps;
      device->setWindowCaption(debug2.c_str());

      smgr->drawAll();
      env->drawAll();
      driver->endScene();
   }
   device->drop();
   NewtonDestroy(nWorld);
   return 0;
}
noals
 
Posts: 32
Joined: Mon Sep 03, 2012 7:59 am

Re: using NewtonCreateHeightFieldCollision

Postby JoeJ » Sun Oct 07, 2012 3:45 am

noals wrote:do you see a problem in my code that could make it crash ?


Run in debug mode. Then you get a detailed error message, and VC jumps to the line of code where the error occured.
You can also use callstack to see which functions where called before.
You can post message and the code where the error happens, if you don't know yourself what's wrong with it.
Try this to make sure the memory is allocated at time where you use it, but i think thats not the reason for the crash:

Code: Select all

    #include <irrlicht.h>
    #include <Newton.h>
    #include "EasyBMP.h"

    BMP heightmap; //bmp image
    u32 heightmapX;
    u32 heightmapY;

//float* heightmapData = new float [256*256]; // allocate memory at runtime

    int main()
    {
float* heightmapData = new float [256*256]; // allocate memory here
if (heightmapData  == 0) return 0; // no memory available
       //init newton
       NewtonWorld*nWorld=NewtonCreate();

       //load the heightmap
       heightmap.ReadFromFile("heightmap/F18.bmp");
       //heightmapData
       for(heightmapX=0;heightmapX<heightmap.TellHeight();heightmapX++)
       {
          for(heightmapY=0;heightmapY<heightmap.TellWidth();heightmapY++)
          {
               RGBApixel pixelTemp = heightmap.GetPixel(heightmapX,heightmapY);
heightmapData [heightmapX + heightmapY*256] = float(pixelTemp.Red) / 255.0; // 0...1
          }
       }

       //Newton
       NewtonCollision* nTerrainCol = NewtonCreateHeightFieldCollision(
          nWorld,         //world pointer
          256,         //width
          256,            //height
          0,            //diagonal cut
          heightmapData,      //unsigned short* elevationMap - the actual elevation map as 16-bit integer array from ram
          0,
          400.0f,         //calcul one cell, check irrlicht scaling
          33.0f);         //maximum height
       NewtonBody* nTerrain=NewtonCreateDynamicBody(nWorld, nTerrainCol,0);
       NewtonDestroyCollision(nTerrainCol);

       while(device->run())
       if(device->isWindowActive())
       {
       }

       NewtonDestroy(nWorld);
delete [] heightmapData; // dont forget to free the memory when you don't need it anymore
    }

User avatar
JoeJ
 
Posts: 1489
Joined: Tue Dec 21, 2010 6:18 pm

Re: using NewtonCreateHeightFieldCollision

Postby noals » Sun Oct 07, 2012 5:31 am

i followed a little tuto to run in debug mode.
it say me that :
Could not load terrain, because file could not be opened.: heightmap/F18.bmp
Could not open file of texture: texture/herbe.jpg

and then messages like that :
First-chance exception at 0x0041d840 in Irrlicht_Newton.exe: 0xC0000005: Access violation reading location 0x00000000.
Unhandled exception at 0x0041d840 in Irrlicht_Newton.exe: 0xC0000005: Access violation reading location 0x00000000.


dunno...
i first though it could be a conflict between easyBMP and irrlicht but since i dont have this problem when i dont use newton, it dont make sense at all.

im disappointed.
noals
 
Posts: 32
Joined: Mon Sep 03, 2012 7:59 am

Re: using NewtonCreateHeightFieldCollision

Postby JoeJ » Sun Oct 07, 2012 10:56 am

noals wrote:First-chance exception at 0x0041d840 in Irrlicht_Newton.exe: 0xC0000005: Access violation reading location 0x00000000.


This is a thing that happens very often.
Example:

int *pointer = 0;
int content = *pointer; // after the crash VC should bring you to this code line, so yopu easily find the place where something goes wrong - if this does not happen, you need to dig in further about debugging.

... we set a pointer, but instead of pointing it to memory, we leave it to zero.
Cpu knows that this must be a mistake and detects it as a bad memory access.

This works:

int foo = 11;
int *pointer = &foo;
int content = *pointer;

... now content is 11 too.





noals wrote:Could not load terrain, because file could not be opened.: heightmap/F18.bmp

Maybe, the file is not found and not loaded into memory, thus you have a null pointer?
To check at runtime if pointers are valid, a typical example is:

int *pointer = 0;
pointer = LoadDataFromFile (filename); // this function loads stuff, allocates data and return it, if all is ok - else returns 0
if (pointer == 0)
{
int content = pointer[0]; // now we safely can look at the first piece of data
}
else
{
printf(logfile.txt, "error loading file"); // makes life easier
}


noals wrote:im disappointed.

You have been warned :)
If you implement 3 things, and need all of them to see if all of them work, you have a problem if it does not work from the start (which is mostly the case).
You need to build methods to proof every single little thing alone, otherwise error creeps through dependencies and is har to track down.
Debugging is a good tool to proof.
Try to hit F11. The debugger jumps to the first line of your Main function, and you can hit F10 / F11 to execute a line and jump to the next.
You can observe changing variables and program flow at the same time.
User avatar
JoeJ
 
Posts: 1489
Joined: Tue Dec 21, 2010 6:18 pm

Re: using NewtonCreateHeightFieldCollision

Postby noals » Sun Oct 07, 2012 2:51 pm

// after the crash VC should bring you to this code line, so yopu easily find the place where something goes wrong - if this does not happen, you need to dig in further about debugging.

it return me this line and that is part of code from the irrlicht source ISceneNode.h
Code: Select all
      //! Sets the texture of the specified layer in all materials of this scene node to the new texture.
      /** \param textureLayer Layer of texture to be set. Must be a
      value smaller than MATERIAL_MAX_TEXTURES.
      \param texture New texture to be used. */
      void setMaterialTexture(u32 textureLayer, video::ITexture* texture)
      {
         if (textureLayer >= video::MATERIAL_MAX_TEXTURES)
            return;

this line-->         for (u32 i=0; i<getMaterialCount(); ++i)
            getMaterial(i).setTexture(textureLayer, texture);
      }

You have been warned :)
If you implement 3 things, and need all of them to see if all of them work, you have a problem if it does not work from the start (which is mostly the case).
You need to build methods to proof every single little thing alone, otherwise error creeps through dependencies and is har to track down.
Debugging is a good tool to proof.
Try to hit F11. The debugger jumps to the first line of your Main function, and you can hit F10 / F11 to execute a line and jump to the next.
You can observe changing variables and program flow at the same time.

but it just dont make sense, i want to use a physic engine, not to fight against logic itself... ><
my code work well without newton and it tell me that it isnt newton the problem...
i cant continue like that.

thx for your help anyway.
noals
 
Posts: 32
Joined: Mon Sep 03, 2012 7:59 am

Previous

Return to General Discussion

Who is online

Users browsing this forum: No registered users and 1 guest

cron