Суббота, 20.04.2024, 09:31
Приветствую Вас Гость

IrrPhysX russian community

Меню сайта
Категории раздела
Irrlicht & IrrPhysX [4]
статьи по использованию Irrlicht и IrrPhysX
IrrLicht [3]
статью по иррлихту
Мини-чат
Наш опрос
Оцените мой сайт
Всего ответов: 12
Статистика

Онлайн всего: 1
Гостей: 1
Пользователей: 0

баннер

Главная » Статьи » Irrlicht & IrrPhysX

Статья #2 - использование .bsp карт + стрельба шариками)
в первую очередь нужно добавить необходимые компоненты для этого проэкта:

нажмите правой кнопкой по солюшену,найдите "ДОБАВИТЬ" и "существующий элемент"

 и вам необходимо добавить следующие файлы(они есть в каталоге include вашего иррлихта если вы сделали всё,как в было написано в первой статье): 

Code


ShapeCreation.cpp

CGridSceneNode.h

CGridSceneNode.cpp

в результате солюшен должен выглядеть так:

потом, необходимо добавить к началу проэкта #include "ShapeCreation.h":

Code


#include <irrlicht.h>
#include <iostream>
#include <IrrPhysx.h>
#include "ShapeCreation.h"

вот что должно получится в конце...

создаём такой массив

Code


bool keys[irr::KEY_KEY_CODES_COUNT];

после него необходимо создать эвент-ресивер(для чего,обьясню позже)

Code


class MyEventReceiver : public IEventReceiver  
{  
public:  
  virtual bool OnEvent(const SEvent& event)  
  {  
  if(event.EventType == irr::EET_KEY_INPUT_EVENT)  
  {  
  keys[event.KeyInput.Key] = event.KeyInput.PressedDown;  

  }  
  return false; }

для удобства можно выставить неймспейсы,как это сделал я

Code


using namespace irr;
using namespace IrrPhysx;
using namespace core;
using namespace scene;
using namespace video;

теперь нужно создать физзикс менеджер и массив обьектов:

Code


IPhysxManager* physxManager = NULL;
core::array<SPhysxAndNodePair*> objects;
f32 objectDensity = 50;

что такое objectDensity?objectDensity - Это масса обьекта(если масса равна 0 то обьект недвижим)

у нас масса обьектов одна на всех.если хотите, поменяйте или же сделайте каждому обьекту свою массу

теперь начинается самое интересное...входим в процедуру main и там,где у вас вызывается процедура createdevice заменяете текст этой строки на :

Code


MyEventReceiver rv;  
  IrrlichtDevice *device =
  createDevice(driverType, core::dimension2d<s32>(640, 480),24,false,false,false,&rv);

таким образом я прицепил эвент-ресивер к созданному девайсу

чуть далее вставляем такой текст(сейчас я его распишу):

Code


SSceneDesc sceneDesc;
  physxManager = createPhysxManager(device, sceneDesc);
  scene::IMesh* mesh = smgr->getMesh("20kdm2.bsp")->getMesh(0);
  scene::ISceneNode* node = 0;
  SPhysxAndNodePair* pair = new SPhysxAndNodePair;
  core::vector3df pos(0,0,0);
  core::vector3df rot(0,0,0);
  core::vector3df scale(1,1,1);
  for (u32 i = 0 ; i < mesh->getMeshBufferCount() ; i++) {
  IPhysxMesh* physxMesh = physxManager->createTriangleMesh(mesh->getMeshBuffer(i), scale);
  pair->PhysxObject = physxManager->createTriangleMeshObject(physxMesh, scale,rot);
  }
  pair->SceneNode = smgr->addMeshSceneNode(mesh, NULL, -1, pos, rot, scale);
  pair->SceneNode->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
  physxManager->setDebugDataVisible(true);//чтобы убрать полотски,поставьте здесь false
  objects.push_back(pair);
  physxManager->setGravity(vector3df(0,-90,0));

---------------------------------------------------------------------------------------------------------

Code


SSceneDesc sceneDesc;
  physxManager = createPhysxManager(device, sceneDesc);

-здесь мы создаём физикс-менеджер(что-то вроде scenemanager'а, только для физзикса)

Code


scene::IMesh* mesh = smgr->getMesh("20kdm2.bsp")->getMesh(0);
  scene::ISceneNode* node = 0;
  SPhysxAndNodePair* pair = new SPhysxAndNodePair;
  core::vector3df pos(0,0,0);
  core::vector3df rot(0,0,0);
  core::vector3df scale(1,1,1);
  for (u32 i = 0 ; i < mesh->getMeshBufferCount() ; i++) {
  IPhysxMesh* physxMesh = physxManager->createTriangleMesh(mesh->getMeshBuffer(i), scale);
  pair->PhysxObject = physxManager->createTriangleMeshObject(physxMesh, scale,rot);
  }
- момент,который подпортил мне немало крови.здесь .bsp карта загружается в PhysX с предустановленными параметрами положения,поворота и масштаба(pos,rot,scale векторы).спросите,а что это там за цикл?дело в том,что .bsp карта содержит сразу кучу мешей,поэтому нужно вот так вот выкручиватся....

как вы заметили,SPhysxAndNodePair содержит в себе и физикс-меш, и обычный нод сцены.над pair->scenenode применимы все операции,что и над обычным нодом сцены

Code


pair->SceneNode = smgr->addMeshSceneNode(mesh, NULL, -1, pos, rot, scale);
  pair->SceneNode->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
  physxManager->setDebugDataVisible(true);
  objects.push_back(pair);
  physxManager->setGravity(vector3df(0,-90,0));

здесь мы добавляем нод сцены к общей сцене,ставим флаги материала,добавляем обьект в массив, и выставляем гравитацию.

далее,в моём исходнике можно будет увидеть такой текст -

Code


camera->setPosition(core::vector3df(1300,144,1249));
  camera->setInputReceiverEnabled(true);

camera->setInputReceiverEnabled(true); выставлять обязательно,если используется эвент-ресивер

ну,и можно конечно выставить far value:

Code


camera->setFarValue(10000);

перед началом цикла while(device->run()) нужен такой текст:

Code
s32 lastTime = device->getTimer()->getTime();

открываем цикл, и...

Code


if(keys[KEY_KEY_C]){objects.push_back(createSphereFromCamera(physxManager, smgr, driver, camera, 50, objectDensity*100));}

добавляем обработку нажатия клавиши C, на нажатию которой будет "вывален" шарик из позиции камеры.

50 - это размер сферы.вы можете поменять его на любой другой,точнотакже как и массу

далее необходимо поставить следующий код:

Code


s32 timeNow = device->getTimer()->getTime();
  s32 elapsedTime = timeNow - lastTime;
  lastTime = timeNow;

  // Set the physics simulation going
  physxManager->simulate(elapsedTime/1000.0f);

  // Whilst we're waiting we can do some non-physics related work
  // you must NEVER add/move physics objects whilst the simulation
  // is being done though, doing so will cause all kinds of horrible crashes!
  core::stringw strw;
  strw = "FPS: ";
  strw += driver->getFPS();

  strw = "Num Objects: ";
  strw += physxManager->getNumPhysxObjects();

  // Wait for the physics simulation to finish
  physxManager->fetchResults();

  // Update our objects to the correct transformations
  for (u32 i = 0 ; i < objects.size() ; i++)  
  objects[i]->updateTransformation();

перед вызовом driver->beginScene(true, true, video::SColor(255,200,200,200));

а после smgr->drawAll(); необходимо поставить physxManager->renderDebugData(video::SColor(0,0,255,255));

вот что должно было получится:

Code


  if(keys[KEY_KEY_C]){objects.push_back(createSphereFromCamera(physxManager, smgr, driver, camera, 50, objectDensity*100));}

  s32 timeNow = device->getTimer()->getTime();
  s32 elapsedTime = timeNow - lastTime;
  lastTime = timeNow;

  // Set the physics simulation going
  physxManager->simulate(elapsedTime/1000.0f);

  // Whilst we're waiting we can do some non-physics related work
  // you must NEVER add/move physics objects whilst the simulation
  // is being done though, doing so will cause all kinds of horrible crashes!
  core::stringw strw;
  strw = "FPS: ";
  strw += driver->getFPS();

  strw = "Num Objects: ";
  strw += physxManager->getNumPhysxObjects();

  // Wait for the physics simulation to finish
  physxManager->fetchResults();

  // Update our objects to the correct transformations
  for (u32 i = 0 ; i < objects.size() ; i++)  
  objects[i]->updateTransformation();
  driver->beginScene(true, true, video::SColor(255,200,200,200));
  smgr->drawAll();
  physxManager->renderDebugData(video::SColor(0,0,255,255));
  driver->endScene();

и там,где у вас device->drop() добавте ещё

Code


removePhysxManager(physxManager);
  physxManager = 0;

вот и всё

вот весь исходник -

Code


/** Example 002 Quake3Map

This Tutorial shows how to load a Quake 3 map into the engine, create a
SceneNode for optimizing the speed of rendering, and how to create a user
controlled camera.

Please note that you should know the basics of the engine before starting this
tutorial. Just take a short look at the first tutorial, if you haven't done
this yet: http://irrlicht.sourceforge.net/tut001.html  

Lets start like the HelloWorld example: We include the irrlicht header files
and an additional file to be able to ask the user for a driver type using the
console.
*/
#include <irrlicht.h>
#include <iostream>
#include <IrrPhysx.h>
#include "ShapeCreation.h"
bool keys[irr::KEY_KEY_CODES_COUNT];
class MyEventReceiver : public IEventReceiver  
{  
public:  
  virtual bool OnEvent(const SEvent& event)  
  {  
  if(event.EventType == irr::EET_KEY_INPUT_EVENT)  
  {  
  keys[event.KeyInput.Key] = event.KeyInput.PressedDown;  

  }  
  return false; }
};
/*
As already written in the HelloWorld example, in the Irrlicht Engine everything
can be found in the namespace 'irr'. To get rid of the irr:: in front of the
name of every class, we tell the compiler that we use that namespace from now
on, and we will not have to write that 'irr::'. There are 5 other sub
namespaces 'core', 'scene', 'video', 'io' and 'gui'. Unlike in the HelloWorld
example, we do not call 'using namespace' for these 5 other namespaces, because
in this way you will see what can be found in which namespace. But if you like,
you can also include the namespaces like in the previous example.
*/
using namespace irr;
using namespace IrrPhysx;
using namespace core;
using namespace scene;
using namespace video;

IPhysxManager* physxManager = NULL;
core::array<SPhysxAndNodePair*> objects;
f32 objectDensity = 50;

/*
Again, to be able to use the Irrlicht.DLL file, we need to link with the
Irrlicht.lib. We could set this option in the project settings, but to make it
easy, we use a pragma comment lib:
*/
#ifdef _MSC_VER
#pragma comment(lib, "Irrlicht.lib")
#pragma comment(lib, "IrrPhysX.lib")  
#pragma comment(lib, "PhysXLoader.lib")
#endif

/*
Ok, lets start. Again, we use the main() method as start, not the WinMain().
*/

int main()
{ MyEventReceiver rv;  

  /*
  Like in the HelloWorld example, we create an IrrlichtDevice with
  createDevice(). The difference now is that we ask the user to select
  which video driver to use. The Software device might be
  too slow to draw a huge Quake 3 map, but just for the fun of it, we make
  this decision possible, too.
  */

  // ask user for driver

  video::E_DRIVER_TYPE driverType;

  printf("Please select the driver you want for this example:\n"\
  " (a) Direct3D 9.0c\n (b) Direct3D 8.1\n (c) OpenGL 1.5\n"\
  " (d) Software Renderer\n (e) Burning's Software Renderer\n"\
  " (f) NullDevice\n (otherKey) exit\n\n");

  char i;
  std::cin >> i;

  switch(i)
  {
  case 'a': driverType = video::EDT_DIRECT3D9;break;
  case 'b': driverType = video::EDT_DIRECT3D8;break;
  case 'c': driverType = video::EDT_OPENGL; break;
  case 'd': driverType = video::EDT_SOFTWARE; break;
  case 'e': driverType = video::EDT_BURNINGSVIDEO;break;
  case 'f': driverType = video::EDT_NULL; break;
  default: return 1;
  }  

  // create device and exit if creation failed

  IrrlichtDevice *device =
  createDevice(driverType, core::dimension2d<s32>(640, 480),24,false,false,false,&rv);

  if (device == 0)
  return 1; // could not create selected driver.

  /*
  Get a pointer to the video driver and the SceneManager so that
  we do not always have to call irr::IrrlichtDevice::getVideoDriver() and
  irr::IrrlichtDevice::getSceneManager().
  */

  for(int x=0; x<irr::KEY_KEY_CODES_COUNT; x++) keys[x] = false;  
  video::IVideoDriver* driver = device->getVideoDriver();
  scene::ISceneManager* smgr = device->getSceneManager();

  /*
  To display the Quake 3 map, we first need to load it. Quake 3 maps
  are packed into .pk3 files which are nothing else than .zip files.
  So we add the .pk3 file to our irr::io::IFileSystem. After it was added,
  we are able to read from the files in that archive as if they are
  directly stored on the disk.
  */
  device->getFileSystem()->addZipFileArchive("../../media/map-20kdm2.pk3");

  /*
  Now we can load the mesh by calling
  irr::scene::ISceneManager::getMesh(). We get a pointer returned to an
  irr::scene::IAnimatedMesh. As you might know, Quake 3 maps are not
  really animated, they are only a huge chunk of static geometry with
  some materials attached. Hence the IAnimatedMesh consists of only one
  frame, so we get the "first frame" of the "animation", which is our
  quake level and create an OctTree scene node with it, using
  irr::scene::ISceneManager::addOctTreeSceneNode().
  The OctTree optimizes the scene a little bit, trying to draw only geometry
  which is currently visible. An alternative to the OctTree would be a
  irr::scene::IMeshSceneNode, which would always draw the complete
  geometry of the mesh, without optimization. Try it: Use
  irr::scene::ISceneManager::addMeshSceneNode() instead of
  addOctTreeSceneNode() and compare the primitives drawn by the video
  driver. (There is a irr::video::IVideoDriver::getPrimitiveCountDrawn()
  method in the irr::video::IVideoDriver class). Note that this
  optimization with the OctTree is only useful when drawing huge meshes
  consisting of lots of geometry.
  */
  SSceneDesc sceneDesc;
  physxManager = createPhysxManager(device, sceneDesc);
  scene::IMesh* mesh = smgr->getMesh("20kdm2.bsp")->getMesh(0);
  scene::ISceneNode* node = 0;
  SPhysxAndNodePair* pair = new SPhysxAndNodePair;
  core::vector3df pos(0,0,0);
  core::vector3df rot(0,0,0);
  core::vector3df scale(1,1,1);
  for (u32 i = 0 ; i < mesh->getMeshBufferCount() ; i++) {
  IPhysxMesh* physxMesh = physxManager->createTriangleMesh(mesh->getMeshBuffer(i), scale);
  pair->PhysxObject = physxManager->createTriangleMeshObject(physxMesh, scale,rot);
  }
  pair->SceneNode = smgr->addMeshSceneNode(mesh, NULL, -1, pos, rot, scale);
  pair->SceneNode->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
  physxManager->setDebugDataVisible(true);
  objects.push_back(pair);
  physxManager->setGravity(vector3df(0,-90,0));

  //if (mesh)
  //node = smgr->addOctTreeSceneNode(mesh, 0, -1, 1024);
// node = smgr->addMeshSceneNode(mesh->getMesh(0));

  /*
  Because the level was not modelled around the origin (0,0,0), we
  translate the whole level a little bit. This is done on
  irr::scene::ISceneNode level using the methods
  irr::scene::ISceneNode::setPosition() (in this case),
  irr::scene::ISceneNode::setRotation(), and
  irr::scene::ISceneNode::setScale().
  */
  //if (node)
  //node->setPosition(core::vector3df(-1300,-144,-1249));

  /*
  Now we only need a camera to look at the Quake 3 map.
  We want to create a user controlled camera. There are some
  cameras available in the Irrlicht engine. For example the
  MayaCamera which can be controlled like the camera in Maya:
  Rotate with left mouse button pressed, Zoom with both buttons pressed,
  translate with right mouse button pressed. This could be created with
  irr::scene::ISceneManager::addCameraSceneNodeMaya(). But for this
  example, we want to create a camera which behaves like the ones in
  first person shooter games (FPS) and hence use
  irr::scene::ISceneManager::addCameraSceneNodeFPS().
  */
  scene::ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS();
  camera->setPosition(core::vector3df(1300,144,1249));
  camera->setInputReceiverEnabled(true);

  /*
  The mouse cursor needs not be visible, so we hide it via the
  irr::IrrlichtDevice::ICursorControl.
  */
  device->getCursorControl()->setVisible(false);
  camera->setFarValue(10000);
  /*
  We have done everything, so lets draw it. We also write the current
  frames per second and the primitives drawn into the caption of the
  window. The test for irr::IrrlichtDevice::isWindowActive() is optional,
  but prevents the engine to grab the mouse cursor after task switching
  when other programs are active. The call to
  irr::IrrlichtDevice::yield() will avoid the busy loop to eat up all CPU
  cycles when the window is not active.
  */
  int lastFPS = -1;
  s32 lastTime = device->getTimer()->getTime();
  while(device->run())
  {  
  if(keys[KEY_KEY_C]){objects.push_back(createSphereFromCamera(physxManager, smgr, driver, camera, 50, objectDensity*100));}

  s32 timeNow = device->getTimer()->getTime();
  s32 elapsedTime = timeNow - lastTime;
  lastTime = timeNow;

  // Set the physics simulation going
  physxManager->simulate(elapsedTime/1000.0f);

  // Whilst we're waiting we can do some non-physics related work
  // you must NEVER add/move physics objects whilst the simulation
  // is being done though, doing so will cause all kinds of horrible crashes!
  core::stringw strw;
  strw = "FPS: ";
  strw += driver->getFPS();

  strw = "Num Objects: ";
  strw += physxManager->getNumPhysxObjects();

  // Wait for the physics simulation to finish
  physxManager->fetchResults();

  // Update our objects to the correct transformations
  for (u32 i = 0 ; i < objects.size() ; i++)  
  objects[i]->updateTransformation();
  driver->beginScene(true, true, video::SColor(255,200,200,200));
  smgr->drawAll();
  physxManager->renderDebugData(video::SColor(0,0,255,255));
  driver->endScene();

  int fps = driver->getFPS();

  if (lastFPS != fps)
  {
  core::stringw str = L"Irrlicht Engine - Quake 3 Map example [";
  str += driver->getName();
  str += "] FPS:";
  str += fps;

  device->setWindowCaption(str.c_str());
  lastFPS = fps;
  }

  }

  /*
  In the end, delete the Irrlicht device.
  */
  removePhysxManager(physxManager);
  physxManager = 0;
  device->drop();
  return 0;
}

/*
That's it. Compile and play around with the program.
**/

вот ссылка на загрузку солюшена - тут

вот билдлог

Code


1>Компиляция...
1>ShapeCreation.cpp
1>main.cpp
1>CGridSceneNode.cpp
1>Создание кода...
1>Компоновка...
1>IrrPhysX.lib(IrrPhysx.obj) : найден .netmodule MSIL или модуль, откомпилированный с параметром /GL; перезапускается компоновка с параметром /LTCG; добавьте /LTCG в командную строку компоновки для повышения производительности компоновщика
1>Создание кода
1>Создание кода завершено
1>Внедрение манифеста...
1>Журнал построения был сохранен в "file://h:\site articles\irrlicht-1.5\examples\02.Quake3Map\Release\BuildLog.htm"
1>02.Quake3Map - ошибок 0, предупреждений 0
========== Перестроение всех: успешно: 1, с ошибками: 0, пропущено: 0 ==========

скриншот моих трудов)

Категория: Irrlicht & IrrPhysX | Добавил: 6opoDa (10.09.2009)
Просмотров: 1335 | Комментарии: 1 | Теги: .bsp, УРОК, пример, стрельба шариками, статья | Рейтинг: 0.0/0 |
Всего комментариев: 1
1 6opoDa  
0
надеюсь,у вас что-то получится после прочтения этой статьи

Имя *:
Email *:
Код *:
информация
Если куда-то нужно добавить новую категорию(например,в каталог статей,или файлов,или ещё куда-нибудь,оставьте просьбу на форуме.после добавления раздела(или НЕ добавления))тема и комментарии будут удалены.писать можно в принципе в любом разделе форума,всёравно удалю)) вопросы лучше задавать всётаки на форуме,или в ПМ, на мыло писать в крайних случаях,потомучто на мыло приходит много спама=)
важно
вся информация,опубликованная на данном ресурсе,свободна для любого использования
любой,кто выкладывает какую-либо информацию на данном ресурсе,соглашается с правилом,указанным выше
при публикации материалов,базированных на материалах ресурса irrphysx.at.ua,на других ресурсах, обязательна ссылка на ресурс irrphysx.at.ua
вся информация предоставляется бесплатно, и администрация не отвечает за действия пользователей
Форма входа
Поиск
Друзья сайта
наша кнопка
код нашей кнопки