Entity *SceneEntityInstance::loadObjectEntryIntoEntity(ObjectEntry *entry, Entity *targetEntity, int entityFileVersion) { Entity *entity = NULL; ObjectEntry *entityType = (*entry)["type"]; if(entityType) { if(entityType->stringVal == "SceneEntityInstance") { ObjectEntry *instanceEntry = (*entry)["SceneEntityInstance"]; String filePath = (*instanceEntry)["filePath"]->stringVal; SceneEntityInstance *instance = new SceneEntityInstance(parentScene, filePath); entity = instance; } else if(entityType->stringVal == "SceneCurve") { ObjectEntry *curveEntry = (*entry)["SceneCurve"]; SceneCurve *curve = new SceneCurve(); if(curveEntry) { curve->renderCurve = (*curveEntry)["render"]->boolVal; curve->curveResolution = (*curveEntry)["resolution"]->intVal; parseObjectIntoCurve((*curveEntry)["curve"], curve->getCurve()); } entity = curve; } else if(entityType->stringVal == "SceneSprite") { ObjectEntry *spriteEntry = (*entry)["SceneSprite"]; String spriteSetName = (*spriteEntry)["sprite_set"]->stringVal; SpriteSet *spriteSet = (SpriteSet*)CoreServices::getInstance()->getResourceManager()->getResourcePoolByName(spriteSetName); if(spriteSet) { SceneSprite *sprite = new SceneSprite(spriteSet); String spriteName = (*spriteEntry)["sprite"]->stringVal; sprite->setSpriteByName(spriteName); String stateName = (*spriteEntry)["state"]->stringVal; if(sprite->getCurrentSprite()) { SpriteState *state = sprite->getCurrentSprite()->getStateByName(stateName); if(state) { sprite->setSpriteState(state, 0, false); } ObjectEntry *randomFrameEntry = (*spriteEntry)["random_frame"]; if(randomFrameEntry) { sprite->setStartOnRandomFrame(randomFrameEntry->boolVal); } } entity = sprite; applySceneMesh((*entry)["SceneMesh"], sprite); } } else if(entityType->stringVal == "SceneLabel") { ObjectEntry *labelEntry = (*entry)["SceneLabel"]; String text = (*labelEntry)["text"]->stringVal; String font = (*labelEntry)["font"]->stringVal; int size = (*labelEntry)["size"]->intVal; Number actualHeight = (*labelEntry)["actualHeight"]->intVal; int aaMode = (*labelEntry)["aaMode"]->intVal; SceneLabel *label = new SceneLabel(text, size, font, aaMode, actualHeight); label->setAnchorPoint(0.0, 0.0, 0.0); label->snapToPixels = false; label->positionAtBaseline = false; applySceneMesh((*entry)["SceneMesh"], label); // RENDERER_TODO /* if(label->getLocalShaderOptions()) { label->getLocalShaderOptions()->clearTexture("diffuse"); label->getLocalShaderOptions()->addTexture("diffuse", label->getTexture()); } */ entity = label; } else if(entityType->stringVal == "SceneParticleEmitter") { ObjectEntry *emitterEntry = (*entry)["SceneParticleEmitter"]; SceneParticleEmitter *emitter = new SceneParticleEmitter(1, 1, 1); emitter->setParticleType((*emitterEntry)["type"]->intVal); emitter->setParticleSpeed((*emitterEntry)["speed"]->NumberVal); emitter->setParticleCount((*emitterEntry)["count"]->intVal); emitter->setParticleLifetime((*emitterEntry)["lifetime"]->NumberVal); emitter->setParticleSize((*emitterEntry)["size"]->NumberVal); emitter->setParticlesInWorldSpace((*emitterEntry)["world"]->boolVal); emitter->setLoopParticles((*emitterEntry)["loop"]->boolVal); emitter->setParticleRotationSpeed(Vector3((*emitterEntry)["rX"]->NumberVal, (*emitterEntry)["rY"]->NumberVal, (*emitterEntry)["rZ"]->NumberVal)); emitter->setGravity(Vector3((*emitterEntry)["gX"]->NumberVal, (*emitterEntry)["gY"]->NumberVal, (*emitterEntry)["gZ"]->NumberVal)); emitter->setParticleDirection(Vector3((*emitterEntry)["dirX"]->NumberVal, (*emitterEntry)["dirY"]->NumberVal, (*emitterEntry)["dirZ"]->NumberVal)); emitter->setEmitterSize(Vector3((*emitterEntry)["eX"]->NumberVal, (*emitterEntry)["eY"]->NumberVal, (*emitterEntry)["eZ"]->NumberVal)); emitter->setDirectionDeviation(Vector3((*emitterEntry)["devX"]->NumberVal, (*emitterEntry)["devY"]->NumberVal, (*emitterEntry)["devZ"]->NumberVal)); emitter->setPerlinEnabled((*emitterEntry)["perlin"]->boolVal); if(emitter->getPerlinEnabled()) { emitter->setPerlinValue(Vector3((*emitterEntry)["pX"]->NumberVal, (*emitterEntry)["pY"]->NumberVal, (*emitterEntry)["pZ"]->NumberVal)); } emitter->useColorCurves = (*emitterEntry)["useColorCurves"]->boolVal; emitter->useScaleCurve = (*emitterEntry)["useScaleCurve"]->boolVal; parseObjectIntoCurve((*emitterEntry)["colorCurveR"], &emitter->colorCurveR); parseObjectIntoCurve((*emitterEntry)["colorCurveG"], &emitter->colorCurveG); parseObjectIntoCurve((*emitterEntry)["colorCurveB"], &emitter->colorCurveB); parseObjectIntoCurve((*emitterEntry)["colorCurveA"], &emitter->colorCurveA); parseObjectIntoCurve((*emitterEntry)["scaleCurve"], &emitter->scaleCurve); applySceneMesh((*entry)["SceneMesh"], emitter); entity = emitter; } else if(entityType->stringVal == "SceneLight") { ObjectEntry *lightEntry = (*entry)["SceneLight"]; if(lightEntry) { int lightType = (*lightEntry)["type"]->intVal; SceneLight *newLight = new SceneLight(lightType, parentScene, 0); newLight->setIntensity((*lightEntry)["intensity"]->NumberVal); ObjectEntry *importanceEntry = (*lightEntry)["importance"]; if(importanceEntry) { newLight->setLightImportance(importanceEntry->intVal); } newLight->setDiffuseLightColor((*lightEntry)["cR"]->NumberVal, (*lightEntry)["cG"]->NumberVal, (*lightEntry)["cB"]->NumberVal, (*lightEntry)["cA"]->NumberVal); newLight->setSpecularLightColor((*lightEntry)["scR"]->NumberVal, (*lightEntry)["scG"]->NumberVal, (*lightEntry)["scB"]->NumberVal, (*lightEntry)["scA"]->NumberVal); newLight->setAttenuation((*lightEntry)["cAtt"]->NumberVal, (*lightEntry)["lAtt"]->NumberVal, (*lightEntry)["qAtt"]->NumberVal); if(newLight->getType() == SceneLight::SPOT_LIGHT) { newLight->setSpotlightProperties((*lightEntry)["spotCutoff"]->NumberVal, (*lightEntry)["spotExponent"]->NumberVal); if((*lightEntry)["shadows"]->boolVal) { newLight->enableShadows(true, (*lightEntry)["shadowmapRes"]->intVal); newLight->setShadowMapFOV((*lightEntry)["shadowmapFOV"]->NumberVal); } } parentScene->addLight(newLight); entity = newLight; } } else if(entityType->stringVal == "ScenePrimitive") { ObjectEntry *scenePrimitiveEntry = (*entry)["ScenePrimitive"]; int pType = (*scenePrimitiveEntry)["type"]->intVal; Number p1 = (*scenePrimitiveEntry)["p1"]->NumberVal; Number p2 = (*scenePrimitiveEntry)["p2"]->NumberVal; Number p3 = (*scenePrimitiveEntry)["p3"]->NumberVal; Number p4 = (*scenePrimitiveEntry)["p4"]->NumberVal; Number p5 = (*scenePrimitiveEntry)["p5"]->NumberVal; ScenePrimitive *primitive = new ScenePrimitive(pType, p1, p2, p3, p4, p5); entity = primitive; applySceneMesh((*entry)["SceneMesh"], primitive); } else if(entityType->stringVal == "SceneMesh") { ObjectEntry *meshEntry = (*entry)["SceneMesh"]; if(meshEntry) { ObjectEntry *fileName = (*meshEntry)["file"]; if(fileName) { SceneMesh *newMesh = new SceneMesh(fileName->stringVal); applySceneMesh(meshEntry, newMesh); // RENDERER_TODO //newMesh->cacheToVertexBuffer(true); entity = newMesh; } } } else if(entityType->stringVal == "SceneSound") { ObjectEntry *soundEntry = (*entry)["SceneSound"]; String filePath = (*soundEntry)["filePath"]->stringVal; Number refDistance = (*soundEntry)["refDistance"]->NumberVal; Number maxDistance = (*soundEntry)["maxDistance"]->NumberVal; Number volume = (*soundEntry)["volume"]->NumberVal; Number pitch = (*soundEntry)["pitch"]->NumberVal; SceneSound *sound = new SceneSound(filePath, refDistance, maxDistance); sound->getSound()->setVolume(volume); sound->getSound()->setPitch(pitch); if((*soundEntry)["loopOnLoad"]) { bool loopOnLoad = (*soundEntry)["loopOnLoad"]->boolVal; sound->setLoopOnLoad(loopOnLoad); if(loopOnLoad) { sound->getSound()->Play(true); } } entity = sound; } else if(entityType->stringVal == "Camera") { ObjectEntry *cameraEntry = (*entry)["Camera"]; Camera *camera = new Camera(parentScene); camera->setExposureLevel((*cameraEntry)["exposure"]->NumberVal); camera->setClippingPlanes((*cameraEntry)["nearClip"]->NumberVal, (*cameraEntry)["farClip"]->NumberVal); camera->setOrthoMode((*cameraEntry)["ortho"]->boolVal); if(camera->getOrthoMode()) { camera->setOrthoSizeMode((*cameraEntry)["sizeMode"]->intVal); camera->setOrthoSize((*cameraEntry)["orthoWidth"]->NumberVal, (*cameraEntry)["orthoHeight"]->NumberVal); } else { camera->setFOV((*cameraEntry)["fov"]->NumberVal); } entity = camera; } } if(!entity) { if(targetEntity) { entity = targetEntity; } else { entity = new Entity(); } } entity->ownsChildren = true; Vector3 bBox; entry->readNumber("bbX", &bBox.x); entry->readNumber("bbY", &bBox.y); entry->readNumber("bbZ", &bBox.z); entity->setLocalBoundingBox(bBox); entity->color.r = (*entry)["cR"]->NumberVal; entity->color.g = (*entry)["cG"]->NumberVal; entity->color.b = (*entry)["cB"]->NumberVal; entity->color.a = (*entry)["cA"]->NumberVal; if(!targetEntity) { entity->setBlendingMode((*entry)["blendMode"]->intVal); entity->setScale((*entry)["sX"]->NumberVal, (*entry)["sY"]->NumberVal, (*entry)["sZ"]->NumberVal); entity->setPosition((*entry)["pX"]->NumberVal, (*entry)["pY"]->NumberVal, (*entry)["pZ"]->NumberVal); if(entityFileVersion > 1) { entity->setRotationQuat((*entry)["rW"]->NumberVal, (*entry)["rX"]->NumberVal, (*entry)["rY"]->NumberVal, (*entry)["rZ"]->NumberVal); } else { entity->setRotationEuler(Vector3((*entry)["rX"]->NumberVal, (*entry)["rY"]->NumberVal, (*entry)["rZ"]->NumberVal)); } } if((*entry)["id"]->stringVal != "") { entity->id = (*entry)["id"]->stringVal; } if((*entry)["layerID"]) { entity->layerID = (unsigned int)((*entry)["layerID"]->intVal); } String tagString = (*entry)["tags"]->stringVal; if(tagString != "") { std::vector<String> tags = tagString.split(","); for(int i=0; i < tags.size(); i++) { entity->addTag(tags[i]); } } ObjectEntry *props = (*entry)["props"]; if(props) { for(int i=0; i < props->length; i++) { ObjectEntry *prop = ((*props))[i]; if(prop) { entity->setEntityProp((*prop)["name"]->stringVal, (*prop)["value"]->stringVal); } } } ObjectEntry *children = (*entry)["children"]; if(children) { for(int i=0; i < children->length; i++) { ObjectEntry *childEntry = ((*children))[i]; ScreenEntity *childEntity = loadObjectEntryIntoEntity(childEntry, NULL, entityFileVersion); entity->addChild(childEntity); } } return entity; }
Water::Water(const Ogre::ConfigFile &mTerrainConfig) { Vector3 mapsize = gEnv->terrainManager->getMaxTerrainSize(); mRenderCamera = gEnv->mainCamera; vRtt1 = vRtt2 = 0; mScale = 1.0f; if (mapsize.x < 1500 && mapsize.z < 1500) mScale = 1.5f; //reading wavefield visible=true; free_wavetrain=0; maxampl=0; haswaves = BSETTING("Waves", false); // disable waves in multiplayer if(gEnv->network) haswaves = false; // parse height float wheight = PARSEREAL(mTerrainConfig.getSetting("WaterLine", "General")); float wbheight = PARSEREAL(mTerrainConfig.getSetting("WaterBottomLine", "General")); // and the type String waterSettingsString = SSETTING("Water effects", "Reflection + refraction (speed optimized)"); if (waterSettingsString == "Basic (fastest)") mType = WATER_BASIC; if (waterSettingsString == "Reflection") mType = WATER_REFLECT; else if (waterSettingsString == "Reflection + refraction (speed optimized)") mType = WATER_FULL_SPEED; else if (waterSettingsString == "Reflection + refraction (quality optimized)") mType = WATER_FULL_QUALITY; if (haswaves) { char line[1024] = {}; FILE *fd = fopen((SSETTING("Config Root", "")+"wavefield.cfg").c_str(), "r"); if (fd) { while (!feof(fd)) { int res = fscanf(fd," %[^\n\r]",line); if (line[0] == ';') continue; float wl,amp,mx,dir; res = sscanf(line,"%f, %f, %f, %f",&wl,&,&mx,&dir); if (res < 4) continue; wavetrains[free_wavetrain].wavelength=wl; wavetrains[free_wavetrain].amplitude=amp; wavetrains[free_wavetrain].maxheight=mx; wavetrains[free_wavetrain].direction=dir/57.0; free_wavetrain++; } fclose(fd); } for (int i=0; i<free_wavetrain; i++) { wavetrains[i].wavespeed=1.25*sqrt(wavetrains[i].wavelength); maxampl+=wavetrains[i].maxheight; } } //theCam=camera; pTestNode=0; waterSceneMgr=gEnv->sceneManager; framecounter=0; height=wheight; orgheight=wheight; rttTex1=0; rttTex2=0; MeshPtr mprt; mReflectCam=0; mRefractCam=0; mapsize = gEnv->terrainManager->getMaxTerrainSize(); //wbuf=0; //ColourValue fade=camera->getViewport()->getBackgroundColour(); ColourValue fade=gEnv->sceneManager->getFogColour(); if (mType == WATER_FULL_QUALITY || mType == WATER_FULL_SPEED || mType == WATER_REFLECT) { // Check prerequisites first const RenderSystemCapabilities* caps = Root::getSingleton().getRenderSystem()->getCapabilities(); if (!caps->hasCapability(RSC_VERTEX_PROGRAM) || !(caps->hasCapability(RSC_FRAGMENT_PROGRAM))) { OGRE_EXCEPT(1, "Your card does not support vertex and fragment programs, so cannot " "run Water effects. Sorry!", "Water effects"); } else { if (!GpuProgramManager::getSingleton().isSyntaxSupported("arbfp1") && !GpuProgramManager::getSingleton().isSyntaxSupported("ps_2_0") && !GpuProgramManager::getSingleton().isSyntaxSupported("ps_1_4") ) { OGRE_EXCEPT(1, "Your card does not support advanced fragment programs, " "so cannot run Water effects. Sorry!", "Water effects"); } } // Ok // Define a floor plane mesh reflectionPlane.normal = Vector3::UNIT_Y; reflectionPlane.d = -wheight+0.15; refractionPlane.normal = -Vector3::UNIT_Y; refractionPlane.d = wheight+0.15; waterPlane.normal = Vector3::UNIT_Y; waterPlane.d = -wheight; if (mType == WATER_FULL_QUALITY || mType == WATER_FULL_SPEED) { TexturePtr rttTex1Ptr = TextureManager::getSingleton().createManual("Refraction", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D, 512, 512, 0, PF_R8G8B8, TU_RENDERTARGET, new ResourceBuffer()); rttTex1 = rttTex1Ptr->getBuffer()->getRenderTarget(); { mRefractCam = gEnv->sceneManager->createCamera("RefractCam"); mRefractCam->setNearClipDistance(mRenderCamera->getNearClipDistance()); mRefractCam->setFarClipDistance(mRenderCamera->getFarClipDistance()); mRefractCam->setAspectRatio( (Real)gEnv->renderWindow->getViewport(0)->getActualWidth() / (Real)gEnv->renderWindow->getViewport(0)->getActualHeight()); vRtt1 = rttTex1->addViewport( mRefractCam ); vRtt1->setClearEveryFrame( true ); vRtt1->setBackgroundColour( fade ); // v->setBackgroundColour( ColourValue::Black ); MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefraction"); mat->getTechnique(0)->getPass(0)->getTextureUnitState(2)->setTextureName("Refraction"); mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefractioninverted"); mat->getTechnique(0)->getPass(0)->getTextureUnitState(2)->setTextureName("Refraction"); vRtt1->setOverlaysEnabled(false); rttTex1->addListener(&mRefractionListener); //optimisation rttTex1->setAutoUpdated(false); // Also clip mRefractCam->enableCustomNearClipPlane(refractionPlane); } } TexturePtr rttTex2Ptr = TextureManager::getSingleton().createManual("Reflection", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D, 512, 512, 0, PF_R8G8B8, TU_RENDERTARGET, new ResourceBuffer()); rttTex2 = rttTex2Ptr->getBuffer()->getRenderTarget(); { mReflectCam = gEnv->sceneManager->createCamera("ReflectCam"); mReflectCam->setNearClipDistance(mRenderCamera->getNearClipDistance()); mReflectCam->setFarClipDistance(mRenderCamera->getFarClipDistance()); mReflectCam->setAspectRatio( (Real)gEnv->renderWindow->getViewport(0)->getActualWidth() / (Real)gEnv->renderWindow->getViewport(0)->getActualHeight()); vRtt2 = rttTex2->addViewport( mReflectCam ); vRtt2->setClearEveryFrame( true ); vRtt2->setBackgroundColour( fade ); // v->setBackgroundColour( ColourValue::Black ); MaterialPtr mat ; if (mType==WATER_FULL_QUALITY || mType==WATER_FULL_SPEED) { mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefraction"); mat->getTechnique(0)->getPass(0)->getTextureUnitState(1)->setTextureName("Reflection"); mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefractioninverted"); mat->getTechnique(0)->getPass(0)->getTextureUnitState(1)->setTextureName("Reflection"); } else { mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflection"); mat->getTechnique(0)->getPass(0)->getTextureUnitState(1)->setTextureName("Reflection"); } vRtt2->setOverlaysEnabled(false); rttTex2->addListener(&mReflectionListener); //optimisation rttTex2->setAutoUpdated(false); // set up linked reflection mReflectCam->enableReflection(waterPlane); // Also clip mReflectCam->enableCustomNearClipPlane(reflectionPlane); } mprt=MeshManager::getSingleton().createPlane("ReflectPlane", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, waterPlane, mapsize.x * mScale,mapsize.z * mScale,WAVEREZ,WAVEREZ,true,1,50,50,Vector3::UNIT_Z, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE); pPlaneEnt = gEnv->sceneManager->createEntity( "plane", "ReflectPlane" ); if (mType==WATER_FULL_QUALITY || mType==WATER_FULL_SPEED) pPlaneEnt->setMaterialName("Examples/FresnelReflectionRefraction"); else pPlaneEnt->setMaterialName("Examples/FresnelReflection"); // gEnv->ogreSceneManager->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); //position pTestNode = gEnv->sceneManager->getRootSceneNode()->createChildSceneNode("WaterPlane"); pTestNode->attachObject(pPlaneEnt); pTestNode->setPosition( Vector3((mapsize.x * mScale)/2,0,(mapsize.z * mScale)/2) ); } else { //basic Water waterPlane.normal = Vector3::UNIT_Y; waterPlane.d = -wheight; mprt=MeshManager::getSingleton().createPlane("WaterPlane", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, waterPlane, mapsize.x * mScale,mapsize.z * mScale,WAVEREZ,WAVEREZ,true,1,50,50,Vector3::UNIT_Z, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE); pPlaneEnt = gEnv->sceneManager->createEntity( "plane", "WaterPlane" ); pPlaneEnt->setMaterialName("tracks/basicwater"); //position pTestNode = gEnv->sceneManager->getRootSceneNode()->createChildSceneNode("WaterPlane"); pTestNode->attachObject(pPlaneEnt); pTestNode->setPosition( Vector3((mapsize.x * mScale)/2,0,(mapsize.z * mScale)/2) ); } //bottom bottomPlane.normal = Vector3::UNIT_Y; bottomPlane.d = -wbheight; //30m below waterline MeshManager::getSingleton().createPlane("BottomPlane", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, bottomPlane, mapsize.x * mScale,mapsize.z * mScale,1,1,true,1,1,1,Vector3::UNIT_Z); Entity *pE = gEnv->sceneManager->createEntity( "bplane", "BottomPlane" ); pE->setMaterialName("tracks/seabottom"); //position pBottomNode = gEnv->sceneManager->getRootSceneNode()->createChildSceneNode("BottomWaterPlane"); pBottomNode->attachObject(pE); pBottomNode->setPosition( Vector3((mapsize.x * mScale)/2,0,(mapsize.z * mScale)/2) ); //setup for waves wbuf=mprt->sharedVertexData->vertexBufferBinding->getBuffer(0); if (wbuf->getSizeInBytes()==(WAVEREZ+1)*(WAVEREZ+1)*32) { wbuffer=(float*)malloc(wbuf->getSizeInBytes()); wbuf->readData(0, wbuf->getSizeInBytes(), wbuffer); } else wbuffer=0; }
void RenderingEngine::Render(const Entity& object) { m_renderProfileTimer.StartInvocation(); GetTexture("displayTexture").BindAsRenderTarget(); //m_window->BindAsRenderTarget(); //m_tempTarget->BindAsRenderTarget(); glClearColor(0.0f,0.0f,0.0f,0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); object.RenderAll(m_defaultShader, *this, *m_mainCamera); for(unsigned int i = 0; i < m_lights.size(); i++) { m_activeLight = m_lights[i]; ShadowInfo shadowInfo = m_activeLight->GetShadowInfo(); int shadowMapIndex = 0; if(shadowInfo.GetShadowMapSizeAsPowerOf2() != 0) shadowMapIndex = shadowInfo.GetShadowMapSizeAsPowerOf2() - 1; assert(shadowMapIndex >= 0 && shadowMapIndex < NUM_SHADOW_MAPS); SetTexture("shadowMap", m_shadowMaps[shadowMapIndex]); m_shadowMaps[shadowMapIndex].BindAsRenderTarget(); glClearColor(1.0f,1.0f,0.0f,0.0f); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); if(shadowInfo.GetShadowMapSizeAsPowerOf2() != 0) { m_altCamera.SetProjection(shadowInfo.GetProjection()); ShadowCameraTransform shadowCameraTransform = m_activeLight->CalcShadowCameraTransform(m_mainCamera->GetTransform().GetTransformedPos(), m_mainCamera->GetTransform().GetTransformedRot()); m_altCamera.GetTransform()->SetPos(shadowCameraTransform.GetPos()); m_altCamera.GetTransform()->SetRot(shadowCameraTransform.GetRot()); m_lightMatrix = BIAS_MATRIX * m_altCamera.GetViewProjection(); SetFloat("shadowVarianceMin", shadowInfo.GetMinVariance()); SetFloat("shadowLightBleedingReduction", shadowInfo.GetLightBleedReductionAmount()); bool flipFaces = shadowInfo.GetFlipFaces(); // const Camera* temp = m_mainCamera; // m_mainCamera = m_altCamera; if(flipFaces) { glCullFace(GL_FRONT); } glEnable(GL_DEPTH_CLAMP); object.RenderAll(m_shadowMapShader, *this, m_altCamera); glDisable(GL_DEPTH_CLAMP); if(flipFaces) { glCullFace(GL_BACK); } // m_mainCamera = temp; float shadowSoftness = shadowInfo.GetShadowSoftness(); if(shadowSoftness != 0) { BlurShadowMap(shadowMapIndex, shadowSoftness); } } else { m_lightMatrix = Matrix4f().InitScale(Vector3f(0,0,0)); SetFloat("shadowVarianceMin", 0.00002f); SetFloat("shadowLightBleedingReduction", 0.0f); } GetTexture("displayTexture").BindAsRenderTarget(); //m_window->BindAsRenderTarget(); // glEnable(GL_SCISSOR_TEST); // TODO: Make use of scissor test to limit light area // glScissor(0, 0, 100, 100); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE); glDepthMask(GL_FALSE); glDepthFunc(GL_EQUAL); object.RenderAll(m_activeLight->GetShader(), *this, *m_mainCamera); glDepthMask(GL_TRUE); glDepthFunc(GL_LESS); glDisable(GL_BLEND); // glDisable(GL_SCISSOR_TEST); } float displayTextureAspect = (float)GetTexture("displayTexture").GetWidth()/(float)GetTexture("displayTexture").GetHeight(); float displayTextureHeightAdditive = displayTextureAspect * GetFloat("fxaaAspectDistortion"); SetVector3f("inverseFilterTextureSize", Vector3f(1.0f/(float)GetTexture("displayTexture").GetWidth(), 1.0f/((float)GetTexture("displayTexture").GetHeight() + displayTextureHeightAdditive), 0.0f)); m_renderProfileTimer.StopInvocation(); m_windowSyncProfileTimer.StartInvocation(); ApplyFilter(m_fxaaFilter, GetTexture("displayTexture"), 0); m_windowSyncProfileTimer.StopInvocation(); }
void ProvidersTest::setup() { //Make a barrel with mass and burn speed properties m_b1 = new Entity("1", 1); m_barrelType = new TypeNode("barrel"); types["barrel"] = m_barrelType; m_b1->setType(m_barrelType); m_b1->setProperty("mass", new SoftProperty(Element(30))); m_b1->setProperty("burn_speed", new SoftProperty(Element(0.3))); m_b1->setProperty("isVisible", new SoftProperty(Element(true))); //List properties for testing list operators SoftProperty* prop1 = new SoftProperty(); prop1->set(std::vector<Element> { 25.0, 20.0 }); m_b1->setProperty("float_list", prop1); SoftProperty* list_prop2 = new SoftProperty(); list_prop2->set(std::vector<Element> { "foo", "bar" }); m_b1->setProperty("string_list", list_prop2); //Make a second barrel m_b2 = new Entity("2", 2); m_b2->setProperty("mass", new SoftProperty(Element(20))); m_b2->setProperty("burn_speed", new SoftProperty(0.25)); m_b2->setType(m_barrelType); m_b2->setProperty("isVisible", new SoftProperty(Element(false))); //Make first barrel contain the second barrel m_b1_container = new LocatedEntitySet; m_b1_container->insert(m_b2); m_b1->m_contains = m_b1_container; //Set bounding box properties for barrels BBoxProperty* bbox1 = new BBoxProperty; //Specify two corners of bbox in form of x, y, z coordinates bbox1->set((std::vector<Element> { -1, -2, -3, 1, 2, 3 })); m_b1->setProperty("bbox", bbox1); BBoxProperty* bbox2 = new BBoxProperty; bbox2->set(std::vector<Element> { -3, -1, -2, 1, 2, 3 }); m_b2->setProperty("bbox", bbox2); ///Set up outfit testing //Green Cloth serves as outfit for gloves m_clothType = new TypeNode("cloth"); types["cloth"] = m_clothType; m_cloth = new Entity("3", 3); m_cloth->setType(m_clothType); m_cloth->setProperty("color", new SoftProperty("green")); //Create outfit map where "thumb" outfit contains cloth std::map<std::string, Element> outfitMap1; outfitMap1.insert(std::make_pair("thumb", Element(m_cloth))); OutfitProperty* outfit2 = new OutfitProperty; outfit2->set(outfitMap1); m_glovesEntity = new Entity("4", 4); m_glovesEntity->setProperty("color", new SoftProperty("brown")); m_glovesEntity->setProperty("outfit", outfit2); //Create outfit map where hands of character contain brown gloves std::map<std::string, Element> outfitMap; outfitMap.insert(std::make_pair("hands", Element(m_glovesEntity))); OutfitProperty* outfit1 = new OutfitProperty; outfit1->set(outfitMap); //Create the character for testing m_characterType = new TypeNode("character"); types["character"] = m_characterType; m_ch1 = new Entity("5", 5); m_ch1->setType(m_characterType); m_ch1->setProperty("outfit", outfit1); //Make second barrel contain the character m_b2_container = new LocatedEntitySet; m_b2_container->insert(m_ch1); m_b2->m_contains = m_b2_container; }
bool ComponentPredicate::operator()(const Entity& entity) { return entity.HasComponent(type); }
/** * First search seeds by OBA strategy, then egment region by seeds with local minimum z-value */ void OBAFilter::segmentRegionBySeeds(const double &seedHeightTh, const double &seedSlopeTh, const double &maxObjSize, const double &seedCellSize, const double &segHeightTh, const double &segSlopeTh) { int ii = 0, count = 0, iy = 0, ix = 0, pos = 0, id = 0, entityID = 0; double ptZ = 0.0; bool *enter_queue = NULL; vector<PT> groundSeeds; vector<PT>::iterator ptIter; PT pt; PointType type; Entity* entity = NULL; PT3D *pt3d; // First dispose garbage this->dispose(); count = this->_gridH * this->_gridW; this->_entityIDs = new int[count]; for(ii = 0; ii < count; ++ii) { this->_entityIDs[ii] = NAN; } enter_queue = new bool[count]; memset(enter_queue, 0, count * sizeof(bool)); // Find ground seeds, and segment from ground seeds calcComplexByObj(this->_workSpace, maxObjSize, seedHeightTh, seedSlopeTh); SeedGenerator seedGenerator(this->_workSpace, maxObjSize, seedCellSize); seedGenerator.findMinSeeds(groundSeeds); for (ptIter = groundSeeds.begin(); ptIter != groundSeeds.end(); ++ptIter) { pt = *ptIter; pos = pt.y * this->_gridW + pt.x; if(this->_entityIDs[pos] != NAN) { continue; } type = PointType::p_ground; entityID++; entity = new Entity(entityID, type); this->_queue.push_back(pt); enter_queue[pos] = true; while(!this->isQueueEmpty()) { pt = this->popQueue(); pos = pt.y * this->_gridW + pt.x; enter_queue[pos] = false; this->_entityIDs[pos] = entityID; pt3d = this->_gridIndex->getMinPT3D(pt.x, pt.y); entity->addPoint(pt, pt3d->z); this->enterQueue(pt, type, enter_queue, segHeightTh, segSlopeTh); } this->_entitys[entityID] = entity; } // Segment for the left points for(iy = 0; iy < this->_gridH; ++iy) { for(ix = 0; ix < this->_gridW; ++ix) { pos = iy * this->_gridW + ix; if(this->_entityIDs[pos] != NAN) { continue; } // Set an object as an unclassified object if it is not a hole type = PointType::p_unclassified; pt3d = this->_gridIndex->getMinPT3D(ix, iy); if(pt3d == NULL) { // Set an object as an created object if it is a hole type = PointType::p_created; } entityID++; entity = new Entity(entityID, type); pt.x = ix; pt.y = iy; this->_queue.push_back(pt); enter_queue[pos] = true; // When the queue is empty, a new object is derived while(!this->isQueueEmpty()) { pt = this->popQueue(); pos = pt.y * this->_gridW + pt.x; enter_queue[pos] = false; pt3d = this->_gridIndex->getMinPT3D(pt.x, pt.y); if(pt3d == NULL) { ptZ = 0.0; } else { ptZ = pt3d->z; } this->_entityIDs[pos] = entityID; entity->addPoint(pt, ptZ); this->enterQueue(pt, type, enter_queue, segHeightTh, segSlopeTh); } this->_entitys[entityID] = entity; } } if(enter_queue != NULL) { delete []enter_queue; enter_queue = NULL; } }
string RocketController::run(string myState) { string game_state_request; for(vector<Entity*>::size_type i = 0; i != controlled_entities.size(); i++) { Entity* ent = controlled_entities[i]; if(ent->getGameState() == myState) { if(ent->getActive()) { //SUBTRACT FUEL SpaceshipComponent* spaceship = (SpaceshipComponent*) ent->getComponent("Spaceship"); float current_fuel = spaceship->getCurrentFuel(); CollectionComponent* collection = (CollectionComponent*) ent->getComponent("Collection"); vector<Entity*> attached_entities = collection->getAttachedEntities(); //Cycling through attached entities for(vector<Entity*>::size_type p = 0; p != attached_entities.size(); p++) { Entity* attached_entity = attached_entities[p]; attached_entity->setActive(true); if(attached_entity->checkIfHasComponent("Rocket")) { RocketComponent* rocket = (RocketComponent*) attached_entity->getComponent("Rocket"); TetheredComponent* tethered = (TetheredComponent*) attached_entity->getComponent("Tethered"); PositionComponent* position = (PositionComponent*) attached_entity->getComponent("Position"); PhysicsComponent* physics = (PhysicsComponent*) attached_entity->getComponent("Physics"); physics->clearForces(); if(rocket->getOnOrOff()) { if(spaceship->getCurrentFuel() - rocket->getFuelConsumption() >= 0) { //The rocket is on float force_exerted = rocket->getForceExerted(); float angle = position->getAngle(); float x = rocket->getForceExerted()*cos(angle); float y = rocket->getForceExerted()*sin(angle); physics->addTranslationalForce(x,y); //Angular Forces float distance = tethered->getDistance(); float angular_force = distance * rocket->getForceExerted() * -sin(tethered->getT()); physics->addAngularForce(angular_force); //Burning fuel spaceship->subtractCurrentFuel(rocket->getFuelConsumption()); } } } } } else { CollectionComponent* collection = (CollectionComponent*) ent->getComponent("Collection"); vector<Entity*> attached_entities = collection->getAttachedEntities(); //Cycling through attached entities for(vector<Entity*>::size_type p = 0; p != attached_entities.size(); p++) { attached_entities[p]->setActive(false); } } } } return game_state_request; }
void RenderingEngine::render(const Entity& entity) const { entity.render(); }
void EC_MediaPlayer::PrepareComponent() { // Don't do anything if rendering is not enabled if (!ViewEnabled() || GetFramework()->IsHeadless()) return; // Some security checks if (componentPrepared_) { LogWarning("EC_MediaPlayer: Preparations seem to be done already, you might not want to do this multiple times."); } if (!mediaPlayer_) { LogError("EC_MediaPlayer: Cannot start preparing, webview object is null. This should never happen!"); return; } // Get parent and connect to the component removed signal. Entity *parent = ParentEntity(); if (parent) connect(parent, SIGNAL(ComponentRemoved(IComponent*, AttributeChange::Type)), SLOT(ComponentRemoved(IComponent*, AttributeChange::Type)), Qt::UniqueConnection); else { LogError("EC_MediaPlayer: Could not get parent entity pointer!"); return; } // Get EC_Mesh component EC_Mesh *mesh = GetMeshComponent(); if (!mesh) { // Wait for EC_Mesh to be added. connect(parent, SIGNAL(ComponentAdded(IComponent*, AttributeChange::Type)), SLOT(ComponentAdded(IComponent*, AttributeChange::Type)), Qt::UniqueConnection); return; } else { // Inspect if this mesh is ready for rendering. EC_Mesh being present != being loaded into Ogre and ready for rendering. if (!mesh->GetEntity()) { connect(mesh, SIGNAL(MeshChanged()), SLOT(TargetMeshReady()), Qt::UniqueConnection); return; } else connect(mesh, SIGNAL(MaterialChanged(uint, const QString&)), SLOT(TargetMeshMaterialChanged(uint, const QString&)), Qt::UniqueConnection); } if (sceneCanvasName_.isEmpty()) sceneCanvasName_ = "VlcMediaPlayerCanvas-" + QUuid::createUuid().toString().replace("{", "").replace("}", ""); // Get or create local EC_WidgetCanvas component ComponentPtr iComponent = parent->GetOrCreateComponent(EC_WidgetCanvas::TypeNameStatic(), sceneCanvasName_, AttributeChange::LocalOnly, false); EC_WidgetCanvas *sceneCanvas = dynamic_cast<EC_WidgetCanvas*>(iComponent.get()); if (!sceneCanvas) { LogError("EC_MediaPlayer: Could not get or create EC_WidgetCanvas component!"); return; } sceneCanvas->SetTemporary(true); sceneCanvas->SetSelfIllumination(getilluminating()); // All the needed components are present, mark prepared as true. componentPrepared_ = true; // We are now prepared, check enabled state and restore possible materials now if (!getenabled()) sceneCanvas->RestoreOriginalMeshMaterials(); // Show downloading info icon or if not downloading, // ask for a image update from the player if (pendingMediaDownload_) OnFrameUpdate(downloadingLogo_); else mediaPlayer_->ForceUpdateImage(); }
void RiseDeadSpell::Update(float timeDelta) { if(m_creationFailed) { m_light = LightHandle(); return; } m_duration+=200; m_fissure.Update(timeDelta); m_fissure.Render(); if(lightHandleIsValid(m_light)) { EERIE_LIGHT * light = lightHandleGet(m_light); light->intensity = 0.7f + 2.3f; light->fallend = 500.f; light->fallstart = 400.f; light->rgb = Color3f(0.8f, 0.2f, 0.2f); light->duration=800; light->time_creation = (unsigned long)(arxtime); } unsigned long tim = m_fissure.ulCurrentTime; if(tim > 3000 && m_entity == EntityHandle() && !m_creationFailed) { ARX_SOUND_PlaySFX(SND_SPELL_ELECTRIC, &m_targetPos); Cylinder phys = Cylinder(m_targetPos, 50, -200); float anything = CheckAnythingInCylinder(phys, NULL, CFLAG_JUST_TEST); if(glm::abs(anything) < 30) { const char * cls = "graph/obj3d/interactive/npc/undead_base/undead_base"; Entity * io = AddNPC(cls, -1, IO_IMMEDIATELOAD); if(io) { ARX_INTERACTIVE_HideGore(io); RestoreInitialIOStatusOfIO(io); io->summoner = m_caster; io->ioflags|=IO_NOSAVE; m_entity = io->index(); io->scriptload=1; ARX_INTERACTIVE_Teleport(io, phys.origin); SendInitScriptEvent(io); if(ValidIONum(m_caster)) { EVENT_SENDER = entities[m_caster]; } else { EVENT_SENDER = NULL; } SendIOScriptEvent(io,SM_SUMMONED); Vec3f pos = m_fissure.m_eSrc; pos += randomVec3f() * 100.f; pos += Vec3f(-50.f, 50.f, -50.f); MakeCoolFx(pos); } m_light = LightHandle(); } else { ARX_SOUND_PlaySFX(SND_MAGIC_FIZZLE); m_creationFailed = true; m_duration=0; } } else if(!arxtime.is_paused() && tim < 4000) { if(Random::getf() > 0.95f) { MakeCoolFx(m_fissure.m_eSrc); } } }
void CreateFieldSpell::Launch() { unsigned long start = (unsigned long)(arxtime); if(m_flags & SPELLCAST_FLAG_RESTORE) { start -= std::min(start, 4000ul); } m_timcreation = start; m_duration = (m_launchDuration > -1) ? m_launchDuration : 800000; m_hasDuration = true; m_fManaCostPerSecond = 1.2f; Vec3f target; float beta = 0.f; bool displace = false; if(m_caster == PlayerEntityHandle) { target = entities.player()->pos; beta = player.angle.getPitch(); displace = true; } else { if(ValidIONum(m_caster)) { Entity * io = entities[m_caster]; target = io->pos; beta = io->angle.getPitch(); displace = (io->ioflags & IO_NPC) == IO_NPC; } else { ARX_DEAD_CODE(); } } if(displace) { target += angleToVectorXZ(beta) * 250.f; } ARX_SOUND_PlaySFX(SND_SPELL_CREATE_FIELD, &target); res::path cls = "graph/obj3d/interactive/fix_inter/blue_cube/blue_cube"; Entity * io = AddFix(cls, -1, IO_IMMEDIATELOAD); if(io) { ARX_INTERACTIVE_HideGore(io); RestoreInitialIOStatusOfIO(io); m_entity = io->index(); io->scriptload = 1; io->ioflags |= IO_NOSAVE | IO_FIELD; io->initpos = io->pos = target; SendInitScriptEvent(io); m_field.Create(target); m_field.SetDuration(m_duration); m_field.lLightId = GetFreeDynLight(); if(lightHandleIsValid(m_field.lLightId)) { EERIE_LIGHT * light = lightHandleGet(m_field.lLightId); light->intensity = 0.7f + 2.3f; light->fallend = 500.f; light->fallstart = 400.f; light->rgb = Color3f(0.8f, 0.0f, 1.0f); light->pos = m_field.eSrc - Vec3f(0.f, 150.f, 0.f); } m_duration = m_field.GetDuration(); if(m_flags & SPELLCAST_FLAG_RESTORE) { m_field.Update(4000); } } else { m_duration = 0; } }
/** \brief Size, in bytes, of the field data for each entity */ inline unsigned field_data_size( const FieldBase & f , const Entity & e ) { return field_data_size( f , e.bucket() ); }
/** \brief Check for existence of field data. * * \exception std::runtime_error * Thrown if required_by != NULL and the field data does not exist. */ inline bool field_data_valid( const FieldBase & f , const Entity & e , const char * required_by = NULL ) { return field_data_valid( f, e.bucket(), e.bucket_ordinal(), required_by ); }
TransformationData SharedManipulationMerger::calculateResult() { TransformationData result; unsigned temp; unsigned short objectType; unsigned short objectId; unsigned entityId; unsigned tempObjectType, tempObjectId; bool tempBool; uint64_t pipeId = inputPipeList[0].pipe->getPipeId(); TransformationManager::unpackPipeId(pipeId, &temp, &temp, &temp, &temp, &tempObjectType, &tempObjectId, &tempBool); objectType = (unsigned short)tempObjectType; objectId = (unsigned short)tempObjectId; entityId = join(objectType, objectId); Entity* ent; if (inputPipeList.size() == 1) { // do what offset modifier does TransformationData resultLastStage; User* user = inputPipeList[0].pipe->getOwner(); TransformationData offset = user->getAssociatedEntityOffset(entityId); resultLastStage = inputPipeList[0].transf; multiply(result, resultLastStage, offset); // dumpVec(resultLastStage.position, "SharedManipulationMerger: cursor transf"); // dumpVec(offset.position, "SharedManipulationMerger: picking offset"); // assert(false); singleUser = true; } else if (singleUser) { // got two users the first time assert(inputPipeList.size() == 2); gmtl::Vec3f center; gmtl::Vec3f cursor[2]; TransformationData entTransf; int i; for (i = 0; i < 2; i++) cursor[i] = inputPipeList[i].transf.position; center = (cursor[0] + cursor[1]) * 0.5f; ent = WorldDatabase::getEntityWithTypeInstanceId(objectType, objectId); assert(ent); entTransf = ent->getWorldTransformation(); scale = entTransf.scale; dumpTransformation(entTransf); dEntityOrigin = entTransf.position - center; axis = cursor[1] - cursor[0]; gmtl::normalize(axis); orientation = entTransf.orientation; if (gmtl::length(cursor[0]) < 0.001f || gmtl::length(cursor[1]) < 0.001f) { assert(false); } singleUser = false; result = entTransf; } else { // multiuser gmtl::Vec3f center; gmtl::Vec3f cursor[2]; gmtl::Vec3f axisNew; gmtl::Vec3f normal; gmtl::AxisAnglef rotAngle; gmtl::Quatf rotq; TransformationData entTransf; float dotProduct; float angle; int i; for (i = 0; i < 2; i++) cursor[i] = inputPipeList[i].transf.position; center = (cursor[0] + cursor[1]) * 0.5f; axisNew = cursor[1] - cursor[0]; gmtl::normalize(axisNew); // printd("Normal = %f %f %f\n", normal[0], normal[1], normal[2]); // printd("angle = %f\n", angle); dotProduct = gmtl::dot(axis, axisNew); // if(fabs(dotProduct) > 1) // { // printd("axis are very similar\n"); // // gmtl::Vec3f li = axis + gmtl::Vec3f(1, 0, 0); // gmtl::Vec3f li; // gmtl::Quatf invOri; // gmtl::Matrix44f rotm; // // invOri = orientation; // invert(invOri); // li = invOri * gmtl::Vec3f(1, 0, 0); // normalize(li); // if(fabs(gmtl::dot(li, axis)) >= 0.99999) // { // printd("ohoh right and axis are not linear independent\n"); // li = invOri * gmtl::Vec3f(0, 0, 1); // normalize(li); // assert(fabs(gmtl::dot(li, axis)) < 1); // } // // // normalize(li); // gmtl::cross(normal, axis, li); // normalize(normal); // gmtl::cross(li, normal, axis); // normalize(li); // // rotm.set( li[0], li[1], li[2], 0, // normal[0], normal[1], normal[2], 0, // axis[0], axis[1], axis[2], 0, // 0, 0, 0, 1); // // assert(gmtl::length(li) < 1.01); // assert(gmtl::length(normal) < 1.01); // assert(gmtl::length(axis) < 1.01); // // printd("det of rotm: %0.03f\n", gmtlDet3(rotm)); // gmtl::set(rotq, rotm); // // } else // { // gmtl::cross(normal, axis, axisNew); // gmtl::normalize(normal); // angle = acos(dotProduct); // rotAngle = gmtl::AxisAnglef(angle, normal); // gmtl::set(rotq, rotAngle); // } gmtl::cross(normal, axis, axisNew); gmtl::normalize(normal); if (gmtl::length(normal) < 0.99999) { printd("bad normal: %0.04f\n", gmtl::length(normal)); normal = gmtl::Vec3f(1, 0, 0); angle = 0; rotq = gmtl::QUAT_IDENTITYF; } // if else { dotProduct = gmtl::dot(axis, axisNew); if (dotProduct > 1) dotProduct = 1; if (dotProduct < -1) dotProduct = -1; angle = acos(dotProduct); // printd("Normal length = %f\n", gmtl::length(normal)); // printd("Angle = %f\n", angle); rotAngle = gmtl::AxisAnglef(angle, normal); gmtl::set(rotq, rotAngle); // printd("Quaternion = %f %f %f %f\n", rotq[0], rotq[1], rotq[2], rotq[3]); } // else dEntityOrigin = rotq * dEntityOrigin; orientation = rotq * orientation; axis = axisNew; result = identityTransformation(); result.position = center + dEntityOrigin; result.orientation = orientation; result.scale = scale; // dumpTransformation(result); #if not defined(MACOS_X) && not defined(__APPLE_CC__) if (isnan(result.position[0])) { dumpTransformation(result); assert(false); } #endif } // else return result; }
// Filetering method void OBAFilter::filterRegion(const double &filteringHeightTh, const double &filteringSlopeTh, const double &dtmFactor, const double &objectHT) { bool *groundTag = NULL; int pos1 = 0, pos2 = 0, h = 0, w = 0; Entity *entity = NULL; std::vector<PT> pts; std::vector<PT>::iterator ptIter; float *rasterZ = NULL; PT3D *pt3d = NULL; groundTag = new bool[this->_gridH * this->_gridW]; memset(groundTag, 0, this->_gridH * this->_gridW * sizeof(bool)); this->filterEntitys(); for(hash_map<int, Entity*>::iterator it = this->_entitys.begin(); it != this->_entitys.end(); ++it) { entity = it->second; // Use the type to identify if (entity->getType() == PointType::p_ground) { pts = entity->getAllPts(); for(ptIter = pts.begin(); ptIter != pts.end(); ++ptIter) { pos1 = ptIter->y * this->_gridW + ptIter->x; groundTag[pos1] = true; } } } // Filter the whole region with original LAS file filterPtsByGrid(this->_workSpace, filteringHeightTh, filteringSlopeTh, groundTag); // Interpolate the rasterZ rasterZ = new float[this->_gridH * this->_gridW]; memset(rasterZ, 0, this->_gridH * this->_gridW * sizeof(float)); las2RasterZ(this->_workSpace, this->_gridIndex->getCellSize(), this->_gridW, this->_gridH, rasterZ); for(h = 0; h < this->_gridH; ++h) { for(w = 0; w < this->_gridW; ++w) { pos1 = h * this->_gridW + w; pos2 = (this->_gridH - 1 - h) * this->_gridW + w; groundTag[pos1] = false; if(rasterZ[pos2] == NAN) { continue; } pt3d = this->_gridIndex->getMinPT3D(w, h); if(pt3d == NULL) { continue; } else { if(pt3d->z - rasterZ[pos2] <= 0.5) { groundTag[pos1] = true; entity = this->_entitys[this->_entityIDs[pos1]]; entity->setType(PointType::p_ground); } } } } // Filter the whole region with original LAS file filterPtsByGrid(this->_workSpace, filteringHeightTh, filteringSlopeTh, groundTag); // Interpolate DEM and extract object points las2Raster(this->_workSpace, dtmFactor); extractObjectPoints(this->_workSpace, dtmFactor, objectHT); if (groundTag != NULL) { delete []groundTag; groundTag = NULL; } }
/** * \brief This function is called by the engine when there is a collision with another entity. * \param entity_overlapping the entity overlapping the detector * \param collision_mode the collision mode that detected the collision */ void Block::notify_collision(Entity& entity_overlapping, CollisionMode /* collision_mode */) { entity_overlapping.notify_collision_with_block(*this); }
/** * Filter Entitys */ void OBAFilter::filterEntitys() { hash_map<int, Entity*>::iterator entityIter; Entity *entity = NULL, *nearEntity = NULL; double area = 0.0; std::map<std::string, double> params; std::vector<PT> pts; std::vector<PT>::iterator ptIter; int pos = 0; bool *localEdge = NULL; bool localEdgeTag = false; localEdge = new bool[this->_gridW*this->_gridH]; memset(localEdge, 0, this->_gridW*this->_gridH*sizeof(bool)); getLocalEdge(this->_workSpace, 1.0, localEdge); for(entityIter = this->_entitys.begin(); entityIter != this->_entitys.end(); ++entityIter) { entity = entityIter->second; // Use the type to identify if (entity->getType()!=PointType::p_unclassified) { continue; } // Use area information params = entity->getParameters(); area = params[areaTag]; //Too big if(area == 0.0) { // Too big entity->setType(PointType::p_ground); continue; } // Use edge information localEdgeTag = false; pts = entity->getAllPts(); for(ptIter = pts.begin(); ptIter != pts.end(); ++ptIter) { pos = ptIter->y * this->_gridW + ptIter->x; if(localEdge[pos]) { localEdgeTag = true; break; } } if(!localEdgeTag && area >= 500) { entity->setType(PointType::p_ground); } else { entity->setType(PointType::p_nonground); } } if(localEdge != NULL) { delete []localEdge; localEdge = NULL; } }
/** * \brief Returns whether this entity is an obstacle for another one. * \param other another entity * \return true */ bool Block::is_obstacle_for(Entity& other) { return other.is_block_obstacle(*this); }
int main(int argc, char *argv[]) { SDL_Init(SDL_INIT_VIDEO); displayWindow = SDL_CreateWindow("HW5", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL); SDL_GLContext context = SDL_GL_CreateContext(displayWindow); SDL_GL_MakeCurrent(displayWindow, context); #ifdef _WINDOWS glewInit(); #endif glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearColor(0.0f, 0.3f, 0.5f, 1.0f); SDL_Event event; bool done = false; ShaderProgram program(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl"); glUseProgram(program.programID); Matrix modelMatrix; Matrix modelMatrixc; Matrix viewMatrix; Matrix startMenu; Matrix projectionMatrix; projectionMatrix.setOrthoProjection(-3.55, 3.55, -2.0f, 2.0f, -1.0f, 1.0f); Entity toilet; toilet.player(); vector<Entity> entities; Entity block1; block1.blocks(0.0f, -1.5f); Entity block2; block2.blocks(0.5f, -1.5f); Entity block3; block3.blocks(1.0f, -1.5f); entities.push_back(block1); entities.push_back(block2); entities.push_back(block3); float friction_x = .5f; float friction_y = .1f; //float verticesP1[] = { -3.5f, -1.0f, -2.0f, -1.0f, -2.0f, 0.25f, -3.5f, -1.0f, -2.0f, 0.25f, -3.5f, 0.25f }; float verticesP1[] = { -1.5f, -1.0f, 0.0f, -1.0f, 0.0f, 0.25f, -1.5f, -1.0f, 0.0f, 0.25f, -1.5f, 0.25f }; float texCoords[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 }; //int winner = 0; const int runAnimation[] = { 0, 1, 2, 3, 4, 5, 6 }; //{3,4,5, 15,16,17, 27,28,29, 39,40,41} //{6,7,8, 18,19,20, 30,31,32, 42,43,45} const int numFrames = 7; float animationElapsed = 0.0f; float framesPerSecond = 30.0f; int currentIndex = 0; float lastFrameTicks = 0.0f; const Uint8 *keys = SDL_GetKeyboardState(NULL); std::vector<float> vertexData; std::vector<float> texCoordData; for (int y = 0; y < LEVEL_HEIGHT; y++) { for (int x = 0; x < LEVEL_WIDTH; x++) { if (level1Data[y][x] == 6) { //if 6, put block Entity block1; block1.blocks(y * BLOCK_LENGTH, x * BLOCK_LENGTH); entities.push_back(block1); } } } while (!done) { glClear(GL_COLOR_BUFFER_BIT); program.setModelMatrix(modelMatrix); program.setProjectionMatrix(projectionMatrix); program.setViewMatrix(viewMatrix); //glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, verticesP1); glEnableVertexAttribArray(program.positionAttribute); glEnableVertexAttribArray(program.texCoordAttribute); //glBindTexture(GL_TEXTURE_2D, kyoukoIDLE); //startMenu.setScale(4, 4, 0); glDrawArrays(GL_TRIANGLES, 0, 6); float ticks = (float)SDL_GetTicks() / 1000; float elapsed = ticks - lastFrameTicks; lastFrameTicks = ticks; float fixedElapsed = elapsed; if (fixedElapsed > FIXED_TIMESTEP * MAX_TIMESTEPS) { fixedElapsed = FIXED_TIMESTEP * MAX_TIMESTEPS; } while (fixedElapsed >= FIXED_TIMESTEP) { fixedElapsed -= FIXED_TIMESTEP; } toilet.velocity_x += toilet.acceleration_x *FIXED_TIMESTEP; toilet.velocity_y -= .01f * elapsed; toilet.x += toilet.velocity_x * FIXED_TIMESTEP; toilet.y += toilet.velocity_y *FIXED_TIMESTEP; toilet.matrix.Translate(toilet.velocity_x* FIXED_TIMESTEP, toilet.velocity_x* FIXED_TIMESTEP, 0.0f); for (Entity e : entities){ e.updateImage(texCoords, &program); }; //DrawSpriteSheetSprite(&program, runAnimation[currentIndex], 7, 1, verticesP1, toilet); viewMatrix.setPosition(-toilet.x, -toilet.y, 0); if (keys[SDL_SCANCODE_A]) { animationElapsed += fixedElapsed; if (animationElapsed > 1.0 / framesPerSecond) { currentIndex++; animationElapsed = 0.0; if (currentIndex > numFrames - 1) { currentIndex = 0; } } toilet.x -= framesPerSecond * fixedElapsed / 5; toilet.updateImage(&program, runAnimation[currentIndex], entities); } else if (keys[SDL_SCANCODE_D]) { animationElapsed += fixedElapsed; if (animationElapsed > 1.0 / framesPerSecond) { currentIndex++; animationElapsed = 0.0; if (currentIndex > numFrames - 1) { currentIndex = 0; } } toilet.x += framesPerSecond * fixedElapsed / 5; toilet.updateImage(&program, runAnimation[currentIndex], entities); } else{ currentIndex = 4; toilet.updateImage(&program, runAnimation[currentIndex], entities); } //else if (keys[SDL_SCANCODE_D]) { // if (toilet.x + (framesPerSecond * fixedElapsed) < 1.50f){ // toilet.x += framesPerSecond * fixedElapsed; // // magikarp.matrix.Translate(0, -framesPerSecond * elapsed, 0); // } //} while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) { done = true; } /* if (keys[SDL_SCANCODE_W] && toilet.collideBottom){ toilet.y += framesPerSecond * FIXED_TIMESTEP; toilet.updateImage(&program, runAnimation[currentIndex], entities); }*/ if (keys[SDL_SCANCODE_W]){ toilet.y += framesPerSecond * FIXED_TIMESTEP; toilet.updateImage(&program, runAnimation[currentIndex], entities); } } // glClear(GL_COLOR_BUFFER_BIT); SDL_GL_SwapWindow(displayWindow); } SDL_Quit(); return 0; }
static v8::Handle<v8::Value> notationNameAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.Entity.notationName._get"); Entity* imp = V8Entity::toNative(info.Holder()); return v8StringOrNull(imp->notationName()); }
void Water::PrepareWater() { m_water_plane.normal = Vector3::UNIT_Y; m_water_plane.d = 0; const auto type = App::gfx_water_mode.GetActive(); const bool full_gfx = type == GfxWaterMode::FULL_HQ || type == GfxWaterMode::FULL_FAST; if (full_gfx || type == GfxWaterMode::REFLECT) { // Check prerequisites first const RenderSystemCapabilities* caps = Root::getSingleton().getRenderSystem()->getCapabilities(); if (!caps->hasCapability(RSC_VERTEX_PROGRAM) || !(caps->hasCapability(RSC_FRAGMENT_PROGRAM))) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Your card does not support vertex and fragment programs, so cannot " "run Water effects. Sorry!", "Water effects"); } else { if (!GpuProgramManager::getSingleton().isSyntaxSupported("arbfp1") && !GpuProgramManager::getSingleton().isSyntaxSupported("ps_2_0") && !GpuProgramManager::getSingleton().isSyntaxSupported("ps_1_4") ) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Your card does not support advanced fragment programs, " "so cannot run Water effects. Sorry!", "Water effects"); } } // Ok // Define a floor plane mesh m_reflect_plane.normal = Vector3::UNIT_Y; m_reflect_plane.d = - 0.15; m_refract_plane.normal = -Vector3::UNIT_Y; m_refract_plane.d = 0.15; if (full_gfx) { TexturePtr m_refract_rtt_targetPtr = TextureManager::getSingleton().createManual("Refraction", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D, 512, 512, 0, PF_R8G8B8, TU_RENDERTARGET); m_refract_rtt_texture = m_refract_rtt_targetPtr; m_refract_rtt_target = m_refract_rtt_targetPtr->getBuffer()->getRenderTarget(); { m_refract_cam = gEnv->sceneManager->createCamera("RefractCam"); m_refract_cam->setNearClipDistance(m_render_cam->getNearClipDistance()); m_refract_cam->setFarClipDistance(m_render_cam->getFarClipDistance()); m_refract_cam->setAspectRatio( (Real)RoR::App::GetOgreSubsystem()->GetRenderWindow()->getViewport(0)->getActualWidth() / (Real)RoR::App::GetOgreSubsystem()->GetRenderWindow()->getViewport(0)->getActualHeight()); m_refract_rtt_viewport = m_refract_rtt_target->addViewport(m_refract_cam); m_refract_rtt_viewport->setClearEveryFrame(true); m_refract_rtt_viewport->setBackgroundColour(gEnv->sceneManager->getFogColour()); MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefraction"); mat->getTechnique(0)->getPass(0)->getTextureUnitState(2)->setTextureName("Refraction"); mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefractioninverted"); mat->getTechnique(0)->getPass(0)->getTextureUnitState(2)->setTextureName("Refraction"); m_refract_rtt_viewport->setOverlaysEnabled(false); m_refract_rtt_target->addListener(&m_refract_listener); //optimisation m_refract_rtt_target->setAutoUpdated(false); // Also clip m_refract_cam->enableCustomNearClipPlane(m_refract_plane); } } TexturePtr m_reflect_rtt_targetPtr = TextureManager::getSingleton().createManual("Reflection", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D, 512, 512, 0, PF_R8G8B8, TU_RENDERTARGET); m_reflect_rtt_texture = m_reflect_rtt_targetPtr; m_reflect_rtt_target = m_reflect_rtt_targetPtr->getBuffer()->getRenderTarget(); { m_reflect_cam = gEnv->sceneManager->createCamera("ReflectCam"); m_reflect_cam->setNearClipDistance(m_render_cam->getNearClipDistance()); m_reflect_cam->setFarClipDistance(m_render_cam->getFarClipDistance()); m_reflect_cam->setAspectRatio( (Real)RoR::App::GetOgreSubsystem()->GetRenderWindow()->getViewport(0)->getActualWidth() / (Real)RoR::App::GetOgreSubsystem()->GetRenderWindow()->getViewport(0)->getActualHeight()); m_reflect_rtt_viewport = m_reflect_rtt_target->addViewport(m_reflect_cam); m_reflect_rtt_viewport->setClearEveryFrame(true); m_reflect_rtt_viewport->setBackgroundColour(gEnv->sceneManager->getFogColour()); MaterialPtr mat; if (full_gfx) { mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefraction"); mat->getTechnique(0)->getPass(0)->getTextureUnitState(1)->setTextureName("Reflection"); mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefractioninverted"); mat->getTechnique(0)->getPass(0)->getTextureUnitState(1)->setTextureName("Reflection"); } else { mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflection"); mat->getTechnique(0)->getPass(0)->getTextureUnitState(1)->setTextureName("Reflection"); } m_reflect_rtt_viewport->setOverlaysEnabled(false); m_reflect_rtt_target->addListener(&m_reflect_listener); //optimisation m_reflect_rtt_target->setAutoUpdated(false); // set up linked reflection m_reflect_cam->enableReflection(m_water_plane); // Also clip m_reflect_cam->enableCustomNearClipPlane(m_reflect_plane); } m_waterplane_mesh = MeshManager::getSingleton().createPlane("ReflectPlane", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, m_water_plane, m_map_size.x * m_waterplane_mesh_scale, m_map_size.z * m_waterplane_mesh_scale, WAVEREZ, WAVEREZ, true, 1, 50, 50, Vector3::UNIT_Z, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE); m_waterplane_entity = gEnv->sceneManager->createEntity("plane", "ReflectPlane"); if (full_gfx) m_waterplane_entity->setMaterialName("Examples/FresnelReflectionRefraction"); else m_waterplane_entity->setMaterialName("Examples/FresnelReflection"); } else { m_waterplane_mesh = MeshManager::getSingleton().createPlane("WaterPlane", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, m_water_plane, m_map_size.x * m_waterplane_mesh_scale, m_map_size.z * m_waterplane_mesh_scale, WAVEREZ, WAVEREZ, true, 1, 50, 50, Vector3::UNIT_Z, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE); m_waterplane_entity = gEnv->sceneManager->createEntity("plane", "WaterPlane"); m_waterplane_entity->setMaterialName("tracks/basicwater"); } m_waterplane_entity->setCastShadows(false); m_reflect_listener.waterplane_entity = m_waterplane_entity; m_refract_listener.waterplane_entity = m_waterplane_entity; //position m_waterplane_node = gEnv->sceneManager->getRootSceneNode()->createChildSceneNode("WaterPlane"); m_waterplane_node->attachObject(m_waterplane_entity); m_waterplane_node->setPosition(Vector3((m_map_size.x * m_waterplane_mesh_scale) / 2, m_water_height, (m_map_size.z * m_waterplane_mesh_scale) / 2)); //bottom m_bottom_plane.normal = Vector3::UNIT_Y; m_bottom_plane.d = -m_bottom_height; //30m below waterline MeshManager::getSingleton().createPlane("BottomPlane", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, m_bottom_plane, m_map_size.x * m_waterplane_mesh_scale, m_map_size.z * m_waterplane_mesh_scale, 1, 1, true, 1, 1, 1, Vector3::UNIT_Z); Entity* pE = gEnv->sceneManager->createEntity("bplane", "BottomPlane"); pE->setMaterialName("tracks/seabottom"); pE->setCastShadows(false); //position m_bottomplane_node = gEnv->sceneManager->getRootSceneNode()->createChildSceneNode("BottomWaterPlane"); m_bottomplane_node->attachObject(pE); m_bottomplane_node->setPosition(Vector3((m_map_size.x * m_waterplane_mesh_scale) / 2, 0, (m_map_size.z * m_waterplane_mesh_scale) / 2)); //setup for waves m_waterplane_vert_buf = m_waterplane_mesh->sharedVertexData->vertexBufferBinding->getBuffer(0); if (m_waterplane_vert_buf->getSizeInBytes() == (WAVEREZ + 1) * (WAVEREZ + 1) * 32) { m_waterplane_vert_buf_local = (float*)malloc(m_waterplane_vert_buf->getSizeInBytes()); m_waterplane_vert_buf->readData(0, m_waterplane_vert_buf->getSizeInBytes(), m_waterplane_vert_buf_local); } else m_waterplane_vert_buf_local = 0; }
//============================================================================== // void MapEditor::AddBullet() { Entity * tmp = new Bullet(); tmp->setType(ENTITY_TYPE_BULLET); EntityList.push_back(tmp); }
int main( int argc, char* args[] ) { SDL_Color BACKGROUND_COLOR = SDL_Color(); BACKGROUND_COLOR.r = 0; BACKGROUND_COLOR.g = 0; BACKGROUND_COLOR.b = 0; BACKGROUND_COLOR.a = 255; SDL_Color HUNTER_COLOR = SDL_Color(); HUNTER_COLOR.r = 255; HUNTER_COLOR.g = 0; HUNTER_COLOR.b = 0; HUNTER_COLOR.a = 255; SDL_Color BOUND_COLOR = SDL_Color(); BOUND_COLOR.r = 0; BOUND_COLOR.g = 255; BOUND_COLOR.b = 0; BOUND_COLOR.a = 255; SDL_Color PREY_COLOR = SDL_Color(); PREY_COLOR.r = 0; PREY_COLOR.g = 0; PREY_COLOR.b = 255; PREY_COLOR.a = 255; // Init GUI SDL_Window *screen = NULL; if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 ) { std::cout << "Error on SDL_Init:" << std::endl << SDL_GetError() << std::endl; return 1; } screen = SDL_CreateWindow(WINDOW_NAME, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, 0); if( screen == NULL ) { std::cout << "Error on SDL_CreateWindow:" << std::endl << SDL_GetError() << std::endl; return 1; } SDL_Renderer* bgRenderer = NULL; bgRenderer = SDL_CreateRenderer( screen, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if( bgRenderer == NULL ) { std::cout << "Error on SDL_CreateRenderer:" << std::endl << SDL_GetError() << std::endl; return 1; } // Define neural network LinearNeuralNetwork nn = LinearNeuralNetwork( 0, { 1 }, NULL, NULL ); if(std::ifstream(FILENAME)) { nn = LinearNeuralNetwork( FILENAME, Neuron::SIGMOID, Neuron::SIGMOID_DER ); } else { nn = LinearNeuralNetwork( ALPHA, NEURAL_NETWORK_DESCRIPTOR, Neuron::SIGMOID, Neuron::SIGMOID_DER ); } // Inizialization SDL_Rect bounds = SDL_Rect(); bounds.x = BOUND_MIN_X; bounds.y = BOUND_MIN_Y; bounds.w = BOUND_MAX_X - BOUND_MIN_X; bounds.h = BOUND_MAX_Y - BOUND_MIN_Y; Entity hunter = Entity( HUNTER_WIDTH, HUNTER_HEIGHT, HUNTER_SPEED, HUNTER_START_X, HUNTER_START_Y, bounds, HUNTER_COLOR ); Entity prey = Entity( PREY_WIDTH, PREY_HEIGHT, PREY_SPEED, PREY_START_X, PREY_START_Y, bounds, PREY_COLOR ); // Render clr(bgRenderer,BACKGROUND_COLOR); renderRect(bounds, BOUND_COLOR, bgRenderer, false); renderEntity(hunter, bgRenderer); renderEntity(prey, bgRenderer); SDL_RenderPresent(bgRenderer); // TIMERS SDL_TimerID renderTimerId = SDL_AddTimer(TIME_GAP_RENDER, render_callback, NULL); if( renderTimerId == 0 ) { std::cout << "Error on SDL_AddTimer:" << std::endl << SDL_GetError() << std::endl; return 1; } SDL_TimerID movementTimerId = SDL_AddTimer(TIME_GAP_MOVEMENT, movement_callback, NULL); if( movementTimerId == 0 ) { std::cout << "Error on SDL_AddTimer:" << std::endl << SDL_GetError() << std::endl; return 1; } // main cycle //// structure to read user events SDL_Event event; //// to check when the key is pressed or released bool isKeyPressed[4] = { false, false, false, false }; bool quit = false; while( quit == false ) { bool matchIsOver = false; while(!matchIsOver) { // event handling while( SDL_PollEvent( &event ) ) { switch( event.type ) { case SDL_QUIT: quit = true; break; case SDL_KEYDOWN: // Keyboard input handling - keydown checkKeyPressed( event.key.keysym.sym, isKeyPressed, true ); break; case SDL_KEYUP: // Keyboard input handling - keyup checkKeyPressed( event.key.keysym.sym, isKeyPressed, false ); break; case SDL_USEREVENT: switch(event.user.code) { case RENDER_CB: // Render clr(bgRenderer,BACKGROUND_COLOR); renderRect(bounds, BOUND_COLOR, bgRenderer, false); renderEntity(hunter, bgRenderer); renderEntity(prey, bgRenderer); SDL_RenderPresent(bgRenderer); break; case MOVEMENT_CB: int initialDistance = dist(hunter,prey); // Entities movement hunter.move( actHunter(hunter,prey) ); //userMovement(prey, isKeyPressed); // DEBUG std::vector<float> outputNn = outPrey( hunter, prey, nn ); Entity::Action preyAction = actPrey( outputNn ); prey.move( preyAction ); // check contact if( checkContact( hunter, prey ) ) { std::vector<float> err (5, 0); err[preyAction] = - REWARD_CAPTURE * outputNn[preyAction]; nn.learn( err ); matchIsOver = true; } else { int distance = dist(hunter, prey); // std::cout << "distances" << distance << " " << initialDistance << std::endl; std::vector<float> err (5, 0); if( distance > initialDistance ) { err[preyAction] = ( 1 - outputNn[preyAction] ) * REWARD_DISTANCE; } else if( distance < initialDistance ) { err[preyAction] = - outputNn[preyAction] * REWARD_DISTANCE; } nn.learn( err ); } break; // default: // std::cout << "!!! UserEvent code not defined!!!" << std::endl; // return 1; //break; } break; default: break; } } } hunter.reset(); prey.reset(); } SDL_Quit(); return 0; }
TEST(Entity, render) { Entity e = Entity(); Window w({{0,0},{10,10}}); // 10x10 Window in top-left position e.render(w); // Void function - deprecated anyway }
bool World::isActivated(const Entity& entity) const { ANAX_ASSERT(isValid(entity), "invalid entity passed to isActivated"); return m_entityAttributes.attributes[entity.getId().index].activated; }
long DanaeSaveLevel(const fs::path & _fic) { long nb_inter = GetNumberInterWithOutScriptLoad(); // Without Player EERIE_BACKGROUND * eb = ACTIVEBKG; fs::path fic = _fic; fic.set_ext("dlf"); if(fs::exists(fic)) { fs::path backupfile = fic; int i = 0; do { std::stringstream s; s << "dlf_bak_" << i; backupfile.set_ext(s.str()); } while(fs::exists(backupfile) && (i++, true)); if(!fs::rename(fic, backupfile)) { LogError << "Unable to rename file " << fic << " to " << backupfile; return -1; } } fs::path fic2 = fic; fic2.set_ext("llf"); if(fs::exists(fic2)) { fs::path backupfile = fic; int i = 0; do { std::stringstream s; s << "llf_bak_" << i; backupfile.set_ext(s.str()); } while(fs::exists(backupfile) && (i++, true)); if(!fs::rename(fic2, backupfile)) { LogError << "Unable to rename file " << fic2 << " to " << backupfile; return -1; } } DANAE_LS_HEADER dlh; memset(&dlh, 0, sizeof(DANAE_LS_HEADER)); dlh.nb_nodes = CountNodes(); BOOST_STATIC_ASSERT(SAVED_MAX_LINKS == MAX_LINKS); dlh.nb_nodeslinks = SAVED_MAX_LINKS; dlh.nb_lights = 0; // MUST BE 0 !!!! dlh.nb_fogs = ARX_FOGS_Count(); dlh.nb_bkgpolys = BKG_CountPolys(ACTIVEBKG); dlh.nb_childpolys = 0; dlh.nb_ignoredpolys = BKG_CountIgnoredPolys(ACTIVEBKG); dlh.nb_paths = nbARXpaths; long bcount = CountBkgVertex(); size_t allocsize = sizeof(DANAE_LS_HEADER) + sizeof(DANAE_LS_HEADER) * 1 + sizeof(DANAE_LS_INTER) * nb_inter + 512 + sizeof(DANAE_LS_LIGHTINGHEADER) + (bcount + 1) * sizeof(u32) + dlh.nb_nodes * (sizeof(DANAE_LS_NODE) + 64 * dlh.nb_nodeslinks) + dlh.nb_lights * sizeof(DANAE_LS_LIGHT) + 1000000 + nbARXpaths * sizeof(DANAE_LS_PATH) + nbARXpaths * sizeof(DANAE_LS_PATHWAYS) * 30; allocsize = max((size_t)dlh.nb_bkgpolys * (sizeof(u32) + 2) + 1000000, allocsize); char * dat = new char[allocsize]; if(!dat) { LogError << "Unable to allocate Buffer for save..."; return -1; } memset(dat, 0, allocsize); // Preparing HEADER dlh.version = DLH_CURRENT_VERSION; strcpy(dlh.ident, "DANAE_FILE"); dlh.nb_scn = LastLoadedScene.empty() ? 0 : 1; dlh.nb_inter = nb_inter; dlh.nb_zones = 0; dlh.pos_edit = (dlh.nb_scn != 0) ? subj.pos - Mscenepos : subj.pos; dlh.angle_edit = player.angle; dlh.lighting = false; // must be false dlh.time = std::time(NULL); memset(dlh.lastuser, 0, sizeof(dlh.lastuser)); size_t pos = 0; memcpy(dat + pos, &dlh, sizeof(DANAE_LS_HEADER)); pos += sizeof(DANAE_LS_HEADER); // Preparing SCENE DATA if(dlh.nb_scn > 0) { DANAE_LS_SCENE dls; memset(&dls, 0, sizeof(DANAE_LS_SCENE)); strncpy(dls.name, LastLoadedScene.string().c_str(), sizeof(dls.name)); memcpy(dat + pos, &dls, sizeof(DANAE_LS_SCENE)); pos += sizeof(DANAE_LS_SCENE); } // preparing INTER DATA, Ignoring Player Data for(size_t i = 1; i < entities.size(); i++) { if(entities[i] && !entities[i]->scriptload) { Entity * io = entities[i]; DANAE_LS_INTER dli; memset(&dli, 0, sizeof(DANAE_LS_INTER)); if(dlh.nb_scn != 0) { dli.pos = io->initpos - Mscenepos; } else { dli.pos = io->initpos; } dli.angle = io->initangle; strncpy(dli.name, (io->classPath() + ".teo").string().c_str(), sizeof(dli.name)); if(io->ident == 0) { MakeIOIdent(io); } dli.ident = io->ident; if(io->ioflags & IO_FREEZESCRIPT) { dli.flags = IO_FREEZESCRIPT; } memcpy(dat + pos, &dli, sizeof(DANAE_LS_INTER)); pos += sizeof(DANAE_LS_INTER); } } for(size_t i = 0; i < MAX_FOG; i++) { if(fogs[i].exist) { DANAE_LS_FOG dlf; memset(&dlf, 0, sizeof(DANAE_LS_FOG)); dlf.rgb = fogs[i].rgb; dlf.angle = fogs[i].angle; dlf.pos = fogs[i].pos - Mscenepos; dlf.blend = fogs[i].blend; dlf.frequency = fogs[i].frequency; dlf.move = fogs[i].move; dlf.rotatespeed = fogs[i].rotatespeed; dlf.scale = fogs[i].scale; dlf.size = fogs[i].size; dlf.special = fogs[i].special; dlf.speed = fogs[i].speed; dlf.tolive = fogs[i].tolive; memcpy(dat + pos, &dlf, sizeof(DANAE_LS_FOG)); pos += sizeof(DANAE_LS_FOG); } } for(long i = 0; i < nodes.nbmax; i++) { if(nodes.nodes[i].exist) { DANAE_LS_NODE dln; memset(&dln, 0, sizeof(DANAE_LS_NODE)); strcpy(dln.name, nodes.nodes[i].name); dln.pos = nodes.nodes[i].pos - Mscenepos; memcpy(dat + pos, &dln, sizeof(DANAE_LS_NODE)); pos += sizeof(DANAE_LS_NODE); for(size_t j = 0; j < SAVED_MAX_LINKS; j++) { char name[64]; memset(name, 0, 64); if(nodes.nodes[i].link[j] != -1 && nodes.nodes[nodes.nodes[i].link[j]].exist) { strcpy(name, nodes.nodes[nodes.nodes[i].link[j]].name); } memcpy(dat + pos, name, 64); pos += 64; } } } for(long i = 0; i < nbARXpaths; i++) { DANAE_LS_PATH dlp; memset(&dlp, 0, sizeof(DANAE_LS_PATH)); dlp.flags = (short)ARXpaths[i]->flags; dlp.idx = 0; dlp.initpos = ARXpaths[i]->initpos - Mscenepos; dlp.pos = ARXpaths[i]->pos - Mscenepos; strncpy(dlp.name, ARXpaths[i]->name.c_str(), sizeof(dlp.name)); dlp.nb_pathways = ARXpaths[i]->nb_pathways; dlp.height = ARXpaths[i]->height; strncpy(dlp.ambiance, ARXpaths[i]->ambiance.string().c_str(), sizeof(dlp.ambiance)); dlp.amb_max_vol = ARXpaths[i]->amb_max_vol; dlp.farclip = ARXpaths[i]->farclip; dlp.reverb = ARXpaths[i]->reverb; dlp.rgb = ARXpaths[i]->rgb; memcpy(dat + pos, &dlp, sizeof(DANAE_LS_PATH)); pos += sizeof(DANAE_LS_PATH); for(long j = 0; j < dlp.nb_pathways; j++) { DANAE_LS_PATHWAYS dlpw; memset(&dlpw, 0, sizeof(DANAE_LS_PATHWAYS)); dlpw.flag = ARXpaths[i]->pathways[j].flag; dlpw.rpos = ARXpaths[i]->pathways[j].rpos; float fValue = ARXpaths[i]->pathways[j]._time ; dlpw.time = checked_range_cast<u32>(fValue); memcpy(dat + pos, &dlpw, sizeof(DANAE_LS_PATHWAYS)); pos += sizeof(DANAE_LS_PATHWAYS); } } //Saving Special Polys if(pos > allocsize) { LogError << "Badly Allocated SaveBuffer..." << fic; delete[] dat; return -1; } // Now Saving Whole Buffer fs::ofstream ofs(fic, fs::fstream::out | fs::fstream::binary | fs::fstream::trunc); if(!ofs.is_open()) { LogError << "Unable to open " << fic << " for write..."; delete[] dat; return -1; } if(ofs.write(dat, sizeof(DANAE_LS_HEADER)).fail()) { LogError << "Unable to write to " << fic; delete[] dat; return -1; } size_t cpr_pos = 0; char * compressed = implodeAlloc(dat + sizeof(DANAE_LS_HEADER), pos - sizeof(DANAE_LS_HEADER), cpr_pos); ofs.write(compressed, cpr_pos); delete[] compressed; if(ofs.fail()) { delete[] dat; return false; } ofs.close(); //Now Save Separate LLF Lighting File pos = 0; DANAE_LLF_HEADER llh; memset(&llh, 0, sizeof(DANAE_LLF_HEADER)); // Preparing HEADER llh.version = DLH_CURRENT_VERSION; llh.nb_lights = EERIE_LIGHT_Count(); llh.nb_bkgpolys = BKG_CountPolys(ACTIVEBKG); strcpy(llh.ident, "DANAE_LLH_FILE"); llh.time = std::time(NULL); memset(llh.lastuser, 0, sizeof(llh.lastuser)); memcpy(dat, &llh, sizeof(DANAE_LLF_HEADER)); pos += sizeof(DANAE_LLF_HEADER); for(size_t i = 0; i < MAX_LIGHTS; i++) { EERIE_LIGHT * el = GLight[i]; if(!el || (el->type & TYP_SPECIAL1)) { continue; } DANAE_LS_LIGHT dlight; memset(&dlight, 0, sizeof(DANAE_LS_LIGHT)); dlight.fallend = el->fallend; dlight.fallstart = el->fallstart; dlight.intensity = el->intensity; dlight.pos = el->pos - Mscenepos; dlight.rgb = el->rgb; dlight.extras = el->extras; dlight.ex_flicker = el->ex_flicker; dlight.ex_radius = el->ex_radius; dlight.ex_frequency = el->ex_frequency; dlight.ex_size = el->ex_size; dlight.ex_speed = el->ex_speed; dlight.ex_flaresize = el->ex_flaresize; memcpy(dat + pos, &dlight, sizeof(DANAE_LS_LIGHT)); pos += sizeof(DANAE_LS_LIGHT); } //Saving Special Polys DANAE_LS_LIGHTINGHEADER dll; memset(&dll, 0, sizeof(DANAE_LS_LIGHTINGHEADER)); dll.nb_values = bcount; dll.ModeLight = ModeLight; dll.ViewMode = ViewMode; memcpy(dat + pos, &dll, sizeof(DANAE_LS_LIGHTINGHEADER)); pos += sizeof(DANAE_LS_LIGHTINGHEADER); for(long j = 0; j < eb->Zsize; j++) { for(long i = 0; i < eb->Xsize; i++) { EERIE_BKG_INFO * eg = (EERIE_BKG_INFO *)&eb->Backg[i + j*eb->Xsize]; for(long l = 0; l < eg->nbpoly; l++) { EERIEPOLY * ep = &eg->polydata[l]; if(ep) { long nbvert = (ep->type & POLY_QUAD) ? 4 : 3; for(long k = 0; k < nbvert; k++) { u32 tmp = (u32)ep->v[k].color; memcpy(dat + pos, &tmp, sizeof(u32)); pos += sizeof(u32); } } } } } if(pos > allocsize) { LogError << "Badly allocated save buffer..." << fic2; delete[] dat; return -1; } // Now Saving Whole Buffer ofs.open(fic2, fs::fstream::out | fs::fstream::binary | fs::fstream::trunc); if(!ofs.is_open()) { LogError << "Unable to open " << fic2 << " for write..."; delete[] dat; return -1; } compressed = NULL; cpr_pos = 0; compressed = implodeAlloc(dat, pos, cpr_pos); delete[] dat; ofs.write(compressed, cpr_pos); delete[] compressed; if(ofs.fail()) { LogError << "Unable to Write to " << fic2; return -1; } ADDED_IO_NOT_SAVED = 0; return 1; }
bool World::isActivated(const Entity& entity) const { assert(isValid(entity)); return m_entityAttributes.attributes[entity.getId().index].activated; }
Map * Map::load(const char *buffer) { const char * cursor = buffer; int version = Utils::readInt(&cursor); assert(version == 4); int sizeX = Utils::readInt(&cursor); int sizeY = Utils::readInt(&cursor); Map * map = new Map(); // palette int tileCount = Utils::readInt(&cursor); map->m_palette.push_back(Tile::nullTile()); for (int i = 0; i < tileCount; i++) { Tile * tile = Tile::loadFromMemory(&cursor); map->m_palette.push_back(tile); if (tile == NULL) { delete map; return NULL; } } // layers int layerCount = Utils::readInt(&cursor); map->m_tiles = new Array3<int>(sizeX, sizeY, layerCount); map->m_tiles->clear(); // must be cleared for sparse layers for (int z = 0; z < layerCount; z++) { LayerType layerType = (LayerType)Utils::readInt(&cursor); switch (layerType) { case ltFull: for (int y = 0; y < sizeY; y++) for (int x = 0; x < sizeX; x++) map->m_tiles->set(x, y, z, Utils::readInt(&cursor)); break; case ltSparse: { int tileCount = Utils::readInt(&cursor); for (int i = 0; i < tileCount; i++) { SparseTile * sparseTile = Utils::readStruct<SparseTile>(&cursor); map->m_tiles->set(sparseTile->x, sparseTile->y, z, sparseTile->tile); } break; } default: assert(false); } } // submaps int submapCount = Utils::readInt(&cursor); assert(submapCount == 0); // triggers int triggerCount = Utils::readInt(&cursor); assert(triggerCount == 0); // entities int entityCount = Utils::readInt(&cursor); for (int i = 0; i < entityCount; i++) { int x = Utils::readInt(&cursor); int y = Utils::readInt(&cursor); int layer = Utils::readInt(&cursor); std::string id = Utils::readString(&cursor); Entity * entity = ResourceManager::getEntity(id); if (entity == NULL) { delete map; return NULL; } entity->setCenter(x, y); entity->setLayer(layer); map->m_entities.push_back(entity); } map->calculateBoundaries(); return map; }
void DotSceneLoader::processEntity(TiXmlElement *XMLNode, SceneNode *pParent) { numObjects++; // Process attributes String name = getAttrib(XMLNode, "name"); String id = getAttrib(XMLNode, "id"); String meshFile = getAttrib(XMLNode, "meshFile"); String materialFile = getAttrib(XMLNode, "materialFile"); bool isStatic = getAttribBool(XMLNode, "static", false);; bool castShadows = getAttribBool(XMLNode, "castShadows", true); Real scalex = getAttribReal(XMLNode,"scaleU",1); Real scaley = getAttribReal(XMLNode,"scaleV",1); Real scrollx = getAttribReal(XMLNode,"scrollU",0); Real scrolly = getAttribReal(XMLNode,"scrollV",0); // TEMP: Maintain a list of static and dynamic objects if(isStatic) staticObjects.push_back(name); else dynamicObjects.push_back(name); TiXmlElement *pElement; // Process vertexBuffer (?) pElement = XMLNode->FirstChildElement("vertexBuffer"); if(pElement) ;//processVertexBuffer(pElement); // Process indexBuffer (?) pElement = XMLNode->FirstChildElement("indexBuffer"); if(pElement) ;//processIndexBuffer(pElement); // Create the entity Entity* ent = mSceneMgr->createEntity( name, meshFile ); ent->setCastShadows(castShadows); try { MeshManager::getSingleton().load(meshFile, m_sGroupName); /*phys->init(mSceneMgr,mWorld); phys->CreateStaticObject(name,meshFile,pParent); phys->ent->setCastShadows(castShadows);*/ pParent->attachObject(ent); if(!materialFile.empty()) { texture_copy_counter++; MaterialPtr mat = (MaterialPtr)MaterialManager::getSingleton().getByName(materialFile); /*Ogre::Real s; s=(Ogre::Real)mat->getTechnique(0)->getPass(0)->getPointSize(); String str1=_tostr(s/phys->get_z()); String str2=_tostr(s/phys->get_x()); mat->setParameter("scale",str1+" "+str2);*/ mat->clone(_tostr((float)texture_copy_counter)+"_"+mat->getName()); MaterialPtr mat2 = (MaterialPtr)MaterialManager::getSingleton().getByName(_tostr((float)texture_copy_counter)+"_"+mat->getName()); mat2->getTechnique(0)-> getPass(0)->getTextureUnitState(0)->setTextureScale(scalex,scaley); mat2->getTechnique(0)-> getPass(0)->getTextureUnitState(0)->setTextureScroll(scrollx,scrolly); ent->setMaterial(mat2); ent->setMaterialLodBias(90,90,99); } PhysObject* box = new PhysObject(); box->init(mSceneMgr); box->ent=ent; Saver::getSingleton().pushStaticObj(pParent,box,scalex,scaley,scrollx,scrolly,materialFile); } catch(Ogre::Exception &/*e*/) { LogManager::getSingleton().logMessage("[DotSceneLoader] Error loading an entity!"); } // Process userDataReference (?) pElement = XMLNode->FirstChildElement("userDataReference"); if(pElement) processUserDataReference(pElement, ent); }
static void drawDebugMaterials() { if(!ACTIVEBKG || !ACTIVEBKG->exist) { return; } PolyType skip = POLY_NODRAW | POLY_HIDE; if(GInput->isKeyPressed(Keyboard::Key_LeftShift)) { skip |= POLY_TRANS | POLY_WATER; } Vec2f point(DANAEMouse); Entity * owner = GetFirstInterAtPos(Vec2s(point)); TextureContainer * material = NULL; size_t count = 0; Vec2f pp[4]; Vec2f puv[4]; PolyType flags; float minz = std::numeric_limits<float>::max(); for(size_t k = 1; k < entities.size(); k++) { EntityHandle h = EntityHandle(k); if(!entities[h] || !entities[h]->obj) { continue; } Entity * entity = entities[h]; if((entity->ioflags & IO_CAMERA) || (entity->ioflags & IO_MARKER)) continue; if(!(entity->gameFlags & GFLAG_ISINTREATZONE)) continue; if((entity->gameFlags & GFLAG_INVISIBILITY)) continue; if((entity->gameFlags & GFLAG_MEGAHIDE)) continue; switch(entity->show) { case SHOW_FLAG_DESTROYED: continue; case SHOW_FLAG_IN_INVENTORY: continue; case SHOW_FLAG_ON_PLAYER: continue; case SHOW_FLAG_LINKED: break; case SHOW_FLAG_NOT_DRAWN: continue; case SHOW_FLAG_HIDDEN: continue; case SHOW_FLAG_MEGAHIDE: continue; case SHOW_FLAG_KILLED: continue; case SHOW_FLAG_IN_SCENE: break; case SHOW_FLAG_TELEPORTING: break; } if(!entity->bbox2D.valid()) { continue; } for(size_t j = 0; j < entity->obj->facelist.size(); j++) { const EERIE_FACE & face = entity->obj->facelist[j]; if(face.facetype & skip) { continue; } bool valid = true; bool bvalid = false; Vec3f p[3]; Vec2f uv[3]; for(size_t i = 0; i < 3; i++) { unsigned short v = face.vid[i]; valid = valid && v < entity->obj->vertexlist3.size(); if(valid) { if(entity->animlayer[0].cur_anim) { p[i] = entity->obj->vertexlist3[v].vert.p; uv[i] = entity->obj->vertexlist3[v].vert.uv; } else { p[i] = entity->obj->vertexlist[v].vert.p; uv[i] = entity->obj->vertexlist[v].vert.uv; } valid = valid && (p[i].z > 0.000001f); bvalid = bvalid || (p[i].x >= g_size.left && p[i].x < g_size.right && p[i].y >= g_size.top && p[i].y < g_size.bottom); } } if(!valid || !bvalid) { continue; } float z = pointInTriangle(point, p[0], p[1], p[2]); if(z > 0 && z <= minz) { count = 3; for(size_t i = 0; i < count; i++) { pp[i] = Vec2f(p[i].x, p[i].y); puv[i] = uv[i]; } if(face.texid >= 0 && size_t(face.texid) < entity->obj->texturecontainer.size()) { material = entity->obj->texturecontainer[face.texid]; } else { material = NULL; } owner = entity; minz = z; flags = face.facetype & ~(POLY_WATER | POLY_LAVA); } } } for(short z = 0; z < ACTIVEBKG->Zsize; z++) for(short x = 0; x < ACTIVEBKG->Xsize; x++) { const EERIE_BKG_INFO & feg = ACTIVEBKG->fastdata[x][z]; if(!feg.treat) { continue; } for(long l = 0; l < feg.nbpolyin; l++) { EERIEPOLY * ep = feg.polyin[l]; if(!ep) { continue; } if(ep->type & skip) { continue; } bool valid = true; bool bvalid = false; Vec3f p[4]; for(size_t i = 0; i < ((ep->type & POLY_QUAD) ? 4u : 3u); i++) { TexturedVertex tv; tv.p = EE_RT(ep->v[i].p); valid = valid && (tv.p.z > 0.000001f); EE_P(&tv.p, &tv); bvalid = bvalid || (tv.p.x >= g_size.left && tv.p.x < g_size.right && tv.p.y >= g_size.top && tv.p.y < g_size.bottom); p[i] = tv.p; } if(!valid || !bvalid) { continue; } float z = pointInTriangle(point, p[0], p[1], p[2]); if(z <= 0 && (ep->type & POLY_QUAD)) { z = pointInTriangle(point, p[1], p[3], p[2]); } if(z > 0 && z <= minz) { count = ((ep->type & POLY_QUAD) ? 4 : 3); for(size_t i = 0; i < count; i++) { pp[i] = Vec2f(p[i].x, p[i].y); puv[i] = ep->v[i].uv; } material = ep->tex; owner = NULL; minz = z; flags = ep->type; } } } if(count) { GRenderer->SetRenderState(Renderer::DepthTest, false); drawLine2D(pp[0], pp[1], 0.1f, Color::magenta); drawLine2D(pp[2], pp[0], 0.1f, Color::magenta); if(count == 4) { drawLine2D(pp[2], pp[3], 0.1f, Color::magenta); drawLine2D(pp[3], pp[1], 0.1f, Color::magenta); } else { drawLine2D(pp[1], pp[2], 0.1f, Color::magenta); } Vec2f c = Vec2f(0.f); float miny = std::numeric_limits<float>::max(); float maxy = std::numeric_limits<float>::min(); for(size_t i = 0; i < count; i++) { c += pp[i]; miny = std::min(miny, pp[i].y); maxy = std::max(maxy, pp[i].y); } c *= 1.f / count; Vec2f textpos(c.x, miny - 2 * hFontDebug->getLineHeight()); std::ostringstream oss; if(owner) { textpos.y -= hFontDebug->getLineHeight(); } if(material && material->m_pTexture) { textpos.y -= hFontDebug->getLineHeight(); } if((flags & (POLY_WATER | POLY_LAVA)) && enviro && enviro->m_pTexture) { textpos.y -= hFontDebug->getLineHeight(); } if(textpos.y < g_size.top + 5) { textpos.y = maxy + 2 * hFontDebug->getLineHeight(); } if(owner) { drawTextCentered(hFontDebug, textpos, owner->idString(), Color::cyan); textpos.y += hFontDebug->getLineHeight(); } if(material && material->m_pTexture) { drawDebugMaterialTexture(textpos, "Diffuse: ", *material->m_pTexture, Color::green); } if((flags & (POLY_WATER | POLY_LAVA)) && enviro && enviro->m_pTexture) { oss.str(std::string()); oss << "Animation: "; oss << ((flags & (POLY_LAVA)) ? "lava" : "water"); if(flags & POLY_FALL) { oss << " (flowing)"; } drawDebugMaterialTexture(textpos, oss.str(), *enviro->m_pTexture, Color::yellow); } (void)textpos; for(size_t i = 0; i < count; i++) { oss.str(std::string()); oss.setf(std::ios_base::fixed, std::ios_base::floatfield); oss.precision(2); oss << '(' << puv[i].x << ',' << puv[i].y << ')'; std::string text = oss.str(); Vec2f textpos = pp[i]; if(pp[i].y < c.y) { textpos.y -= hFontDebug->getLineHeight(); } if(pp[i].x < c.x) { Vec2i size = hFontDebug->getTextSize(text); textpos.x -= size.x; } hFontDebug->draw(textpos.x, textpos.y, text, Color::gray(0.7f)); } GRenderer->SetRenderState(Renderer::DepthTest, true); } }