예제 #1
0
void Functions::musicBackgroundPlay(Aurora::NWScript::FunctionContext &ctx) {
	Area *area = KotOR::ObjectContainer::toArea(getParamObject(ctx, 0));
	if (area)
		area->playAmbientMusic();
}
예제 #2
0
Area Area::operator+(Area& rv)
{
	return Area(GetValueUnits("m3").Value + rv.GetValueUnits("m3").Value, "m3");
}
예제 #3
0
void SurfaceT<T>::copyFrom( const SurfaceT<T> &srcSurface, const Area &srcArea, const Vec2i &relativeOffset )
{
	std::pair<Area,Vec2i> srcDst = clippedSrcDst( srcSurface.getBounds(), srcArea, getBounds(), srcArea.getUL() + relativeOffset );
	
	if( getChannelOrder() == srcSurface.getChannelOrder() )
		copyRawSameChannelOrder( srcSurface, srcDst.first, srcDst.second );
	else if( hasAlpha() && srcSurface.hasAlpha() )
		copyRawRgba( srcSurface, srcDst.first, srcDst.second );
	else
		copyRawRgb( srcSurface, srcDst.first, srcDst.second );
}
예제 #4
0
파일: main.cpp 프로젝트: gaopu/mygame
//================================================================
int main()
{
	system("mode con: cols=54 lines=26");
	srand((unsigned)time(0));
	enum {_224=224,up=72,down=80,left=75,right=77,space=32,enter=13};//接收上下左右键第一个需要两个变量,第一个值是224
	int score=0,level=0;
	short M=1;
	double _time=0.5;//下降的时间间隔(秒),其实说CLOCKS_PER_SEC在windows下是1000,这里time的单位才可以说是秒)
	//===========================================
	//场地对象
	Area area;
	area.paint();
	//===========================================
	//启动问候语
	gotoxy(10,5);cout<<"俄罗斯方块";
	gotoxy(8,6);
	system("pause");
	gotoxy(10,5);cout<<"         ";
	gotoxy(8,6);cout<<"                   ";
	//===========================================
	gotoxy(area.area_x+11,8);cout<<score;
	gotoxy(area.area_x+11,10);cout<<level;
	clock_t start,end;
	Cube *cube_one=new Cube;//方块1对象
LOOP:
	Cube *cube_two=new Cube;//下一个方块
	cube_two->paint_next(area);
	start=clock();
	cube_one->drop(area);
	while(1)
	{
		end=clock();
		while(_time*CLOCKS_PER_SEC<=end-start)
		{
			if(!cube_one->drop(area))
			{
				if(cube_one->over(area))
				{
					Gameover(area);
				}
				LOOP2:
				delete cube_one;
				cube_one=cube_two;//用2替换1
				goto LOOP;
			}
			start=clock();
		}
		short m;
		if(m=cube_one->clear(area))
		{
			cout<<"\a";
			SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_RED);
			score+=m*10;
			gotoxy(area.area_x+11,8);cout<<score;
			if(score/60>level)
			{
				if(_time>0.1)
				{
					_time-=0.05;
					level=score/60;
					gotoxy(area.area_x+11,10);cout<<level;
				}
				else
				{
					gotoxy(area.area_x+11,10);cout<<"超神级别!";
				}
			}
			goto LOOP2;
		}
		while(kbhit())
		{
			short one,two;
			one=getch();
			switch(one)
			{
			case _224:two=getch();
						switch(two)
						  {
							case up:cube_one->up(area);			break;
							case left:cube_one->left(area);		break;
							case right:cube_one->right(area);	break;
							case down:cube_one->down(area);		break;
							default:							break;
						  }								break;
			case space:cube_one->end(area);				break;//空格到底部
			case enter:getch();							break;//回车是暂停
			default:									break;
			}
		}
		Sleep(1);
	}
	return 0;
}
예제 #5
0
void World::parseZone(YAML::Node fileNode, std::ostream& lerr, TiledLoader* tiledLoader, MobSpawner* mobSpawner) {
    String areaName = readYAMLStr(fileNode, "Area", "nil", "Area expected.", lerr);
    if (areaNameMap.find(areaName) != areaNameMap.end()) {
        String name = readYAMLStr(fileNode, "Name", "nil", "Name expected.", lerr);
        Area* area = areaNameMap[areaName];
        Zone* newZone = NULL;
        if (fileNode["Stack"]) {
            YAML::Node stackNode = fileNode["Stack"];

            String genName = readYAMLStr(fileNode, "Gen", "dungeon");
            GenType gen = GEN_DUNGEON;
            if (genName == "dungeon") gen = GEN_DUNGEON;
            int depth = readYAMLInt(stackNode, "Num_Floors", 10);
            DungeonStack* dungeonStack = new DungeonStack(name, depth, gen);

            String tilesetName = readYAMLStr(stackNode, "Tileset", "nil", "Tileset expected.", lerr);
            if (Tile::hasSet(tilesetName)) {
                dungeonStack->setTileset(Tile::getSet(tilesetName));
            } else lerr << "'" << tilesetName << "' is not an existing tileset.\n";

            dungeonStack->setLight(readYAMLInt(stackNode, "Light", 8), readYAMLNum(stackNode, "LightMod", 0));
            dungeonStack->setNumStairs(readYAMLInt(stackNode, "Stairs", 1), readYAMLNum(stackNode, "StairsMod", 0));
            dungeonStack->setDifficulty(readYAMLInt(stackNode, "Diff", 0), readYAMLNum(stackNode, "DiffMod", 0));

            if (stackNode["Spawn"].IsSequence()) {
                YAML::Node spawnNode = stackNode["Spawn"];
                for (YAML::const_iterator iter = spawnNode.begin(); iter != spawnNode.end(); ++iter) {
                    dungeonStack->addEnvironment(mobSpawner->getEnvironment(iter->as<String>()));
                }
            }
            dungeonStack->createZones();
            newZone = dungeonStack->getZone(0);
            area->addDungeonStack(dungeonStack);
            dunNameMap[name] = dungeonStack;
        } else if (fileNode["File"]) {
            newZone = tiledLoader->loadTileFile(fileNode["File"].as<String>(), name, lerr);
            area->addZone(newZone);
            zoneNameMap[name] = newZone;
        }

        if (newZone && fileNode["Connections"]) {
            YAML::Node cNode = fileNode["Connections"];
            for (YAML::const_iterator iter = cNode.begin(); iter != cNode.end(); ++iter) {
                YAML::Node curNode = *iter;
                if (curNode["From"] && curNode["To"]) {
                    YAML::Node posNode = curNode["From"];
                    Coord pos = Coord(posNode[0].as<int>(), posNode[1].as<int>());
                    String zoneName = curNode["To"].as<String>();
                    if (zoneNameMap.find(zoneName) != zoneNameMap.end()) {
                        area->addConnection(Connection{pos, pos, newZone, zoneNameMap[zoneName]});
                    } else if (dunNameMap.find(zoneName) != dunNameMap.end()) {
                        DungeonStack* ds = dunNameMap[zoneName];
                        area->addConnection(Connection{pos, ds->addEntryStairs(), newZone, ds->getZone(0)});
                    } else lerr << "'" << name << "' is not the name of an existing zone or dungeon stack.\n";
                } else {
                    lerr << "expected From and To in the connection" << std::endl;
                }
            }
        }
    } else lerr << "Area does not exist: " << areaName << "\n";
}
예제 #6
0
void StereoAutoFocuser::autoFocus( CameraStereo *cam, const Area &area, GLuint buffer )
{
	if( !cam->isStereoEnabled() )
		return;

	// create or resize buffers
	createBuffers( area );

	// blit (multi-sampled) depth buffer to (non-multi-sampled) auto focus fbo	
	// (they need to be the same size for this to work!)
	{
		Area dstArea = mFboLarge->getBounds();

		gl::ScopedFramebuffer readBuffer( GL_READ_FRAMEBUFFER, buffer );
		gl::ScopedFramebuffer drawBuffer( GL_DRAW_FRAMEBUFFER, mFboLarge->getId() );

		glBlitFramebuffer( area.getX1(), area.getY1(), area.getX2(), area.getY2(),
						   dstArea.getX1(), dstArea.getY1(), dstArea.getX2(), dstArea.getY2(), GL_DEPTH_BUFFER_BIT, GL_NEAREST );
	}

	// create a downsampled copy for the auto focus test
	{
		Area srcArea = mFboLarge->getBounds();
		Area dstArea = mFboSmall->getBounds();

		gl::ScopedFramebuffer readBuffer( GL_READ_FRAMEBUFFER, mFboLarge->getId() );
		gl::ScopedFramebuffer drawBuffer( GL_DRAW_FRAMEBUFFER, mFboSmall->getId() );

		glBlitFramebuffer( srcArea.getX1(), srcArea.getY1(), srcArea.getX2(), srcArea.getY2(),
						   dstArea.getX1(), dstArea.getY1(), dstArea.getX2(), dstArea.getY2(), GL_DEPTH_BUFFER_BIT, GL_NEAREST );
	}

	// load depth samples into buffer
	glBindFramebuffer( GL_READ_FRAMEBUFFER, mFboSmall->getId() );
	glReadPixels( 0, 0, AF_WIDTH, AF_HEIGHT, GL_DEPTH_COMPONENT, GL_FLOAT, &mBuffer.front() );
	mFboSmall->unbindFramebuffer();

	// find minimum value 
	std::vector<GLfloat>::const_iterator itr = std::min_element( mBuffer.begin(), mBuffer.end() );

	size_t p = itr - mBuffer.begin();
	mNearest.x = 0.5f + (int) ( ( p % AF_WIDTH ) / (float) AF_WIDTH * mArea.getWidth() );
	mNearest.y = 0.5f + (int) ( ( p / AF_WIDTH ) / (float) AF_HEIGHT * mArea.getHeight() );

	// convert to actual distance from camera
	float nearClip = cam->getNearClip();
	float farClip = cam->getFarClip();
	float depth = 2.0f * ( *itr ) - 1.0f;
	mNearest.z = 2.0f * nearClip * farClip / ( farClip + nearClip - depth * ( farClip - nearClip ) );

	// perform auto focussing
	float z = math<float>::max( nearClip, mNearest.z * mDepth );
	cam->setConvergence( cam->getConvergence() + mSpeed * ( z - cam->getConvergence() ), true );
}
예제 #7
0
void AudioStreamPlayer3D::_notification(int p_what) {

	if (p_what == NOTIFICATION_ENTER_TREE) {

		velocity_tracker->reset(get_global_transform().origin);
		AudioServer::get_singleton()->add_callback(_mix_audios, this);
		if (autoplay && !Engine::get_singleton()->is_editor_hint()) {
			play();
		}
	}

	if (p_what == NOTIFICATION_EXIT_TREE) {

		AudioServer::get_singleton()->remove_callback(_mix_audios, this);
	}
	if (p_what == NOTIFICATION_TRANSFORM_CHANGED) {

		if (doppler_tracking != DOPPLER_TRACKING_DISABLED) {
			velocity_tracker->update_position(get_global_transform().origin);
		}
	}

	if (p_what == NOTIFICATION_INTERNAL_PHYSICS_PROCESS) {

		//update anything related to position first, if possible of course

		if (!output_ready) {

			Vector3 linear_velocity;

			//compute linear velocity for doppler
			if (doppler_tracking != DOPPLER_TRACKING_DISABLED) {
				linear_velocity = velocity_tracker->get_tracked_linear_velocity();
			}

			Ref<World> world = get_world();
			ERR_FAIL_COND(world.is_null());

			int new_output_count = 0;

			Vector3 global_pos = get_global_transform().origin;

			int bus_index = AudioServer::get_singleton()->thread_find_bus_index(bus);

			//check if any area is diverting sound into a bus

			PhysicsDirectSpaceState *space_state = PhysicsServer::get_singleton()->space_get_direct_state(world->get_space());

			PhysicsDirectSpaceState::ShapeResult sr[MAX_INTERSECT_AREAS];

			int areas = space_state->intersect_point(global_pos, sr, MAX_INTERSECT_AREAS, Set<RID>(), area_mask);
			Area *area = NULL;

			for (int i = 0; i < areas; i++) {
				if (!sr[i].collider)
					continue;

				Area *tarea = Object::cast_to<Area>(sr[i].collider);
				if (!tarea)
					continue;

				if (!tarea->is_overriding_audio_bus() && !tarea->is_using_reverb_bus())
					continue;

				area = tarea;
				break;
			}

			List<Camera *> cameras;
			world->get_camera_list(&cameras);

			for (List<Camera *>::Element *E = cameras.front(); E; E = E->next()) {

				Camera *camera = E->get();
				Viewport *vp = camera->get_viewport();
				if (!vp->is_audio_listener())
					continue;

				Vector3 local_pos = camera->get_global_transform().orthonormalized().affine_inverse().xform(global_pos);

				float dist = local_pos.length();

				Vector3 area_sound_pos;
				Vector3 cam_area_pos;

				if (area && area->is_using_reverb_bus() && area->get_reverb_uniformity() > 0) {
					area_sound_pos = space_state->get_closest_point_to_object_volume(area->get_rid(), camera->get_global_transform().origin);
					cam_area_pos = camera->get_global_transform().affine_inverse().xform(area_sound_pos);
				}

				if (max_distance > 0) {

					float total_max = max_distance;

					if (area && area->is_using_reverb_bus() && area->get_reverb_uniformity() > 0) {
						total_max = MAX(total_max, cam_area_pos.length());
					}
					if (total_max > max_distance) {
						continue; //cant hear this sound in this camera
					}
				}

				float multiplier = Math::db2linear(_get_attenuation_db(dist));
				if (max_distance > 0) {
					multiplier *= MAX(0, 1.0 - (dist / max_distance));
				}

				Output output;
				output.bus_index = bus_index;
				output.reverb_bus_index = -1; //no reverb by default
				output.viewport = vp;

				float db_att = (1.0 - MIN(1.0, multiplier)) * attenuation_filter_db;

				if (emission_angle_enabled) {
					Vector3 camtopos = global_pos - camera->get_global_transform().origin;
					float c = camtopos.normalized().dot(get_global_transform().basis.get_axis(2).normalized()); //it's z negative
					float angle = Math::rad2deg(Math::acos(c));
					if (angle > emission_angle)
						db_att -= -emission_angle_filter_attenuation_db;
				}

				output.filter_gain = Math::db2linear(db_att);

				Vector3 flat_pos = local_pos;
				flat_pos.y = 0;
				flat_pos.normalize();

				unsigned int cc = AudioServer::get_singleton()->get_channel_count();
				if (cc == 1) {
					// Stereo pair
					float c = flat_pos.x * 0.5 + 0.5;

					output.vol[0].l = 1.0 - c;
					output.vol[0].r = c;
				} else {
					Vector3 camtopos = global_pos - camera->get_global_transform().origin;
					float c = camtopos.normalized().dot(get_global_transform().basis.get_axis(2).normalized()); //it's z negative
					float angle = Math::rad2deg(Math::acos(c));
					float av = angle * (flat_pos.x < 0 ? -1 : 1) / 180.0;

					if (cc >= 1) {
						// Stereo pair
						float fl = Math::abs(1.0 - Math::abs(-0.8 - av));
						float fr = Math::abs(1.0 - Math::abs(0.8 - av));

						output.vol[0].l = fl;
						output.vol[0].r = fr;
					}

					if (cc >= 2) {
						// Center pair
						float center = 1.0 - Math::sin(Math::acos(c));

						output.vol[1].l = center;
						output.vol[1].r = center;
					}

					if (cc >= 3) {
						// Side pair
						float sl = Math::abs(1.0 - Math::abs(-0.4 - av));
						float sr = Math::abs(1.0 - Math::abs(0.4 - av));

						output.vol[2].l = sl;
						output.vol[2].r = sr;
					}

					if (cc >= 4) {
						// Rear pair
						float rl = Math::abs(1.0 - Math::abs(-0.2 - av));
						float rr = Math::abs(1.0 - Math::abs(0.2 - av));

						output.vol[3].l = rl;
						output.vol[3].r = rr;
					}
				}

				for (int k = 0; k < cc; k++) {
					output.vol[k] *= multiplier;
				}

				bool filled_reverb = false;
				int vol_index_max = AudioServer::get_singleton()->get_speaker_mode() + 1;

				if (area) {

					if (area->is_overriding_audio_bus()) {
						//override audio bus
						StringName bus_name = area->get_audio_bus();
						output.bus_index = AudioServer::get_singleton()->thread_find_bus_index(bus_name);
					}

					if (area->is_using_reverb_bus()) {

						filled_reverb = true;
						StringName bus_name = area->get_reverb_bus();
						output.reverb_bus_index = AudioServer::get_singleton()->thread_find_bus_index(bus_name);

						float uniformity = area->get_reverb_uniformity();
						float area_send = area->get_reverb_amount();

						if (uniformity > 0.0) {

							float distance = cam_area_pos.length();
							float attenuation = Math::db2linear(_get_attenuation_db(distance));

							//float dist_att_db = -20 * Math::log(dist + 0.00001); //logarithmic attenuation, like in real life

							float center_val[3] = { 0.5, 0.25, 0.16666 };
							AudioFrame center_frame(center_val[vol_index_max - 1], center_val[vol_index_max - 1]);

							if (attenuation < 1.0) {
								//pan the uniform sound
								Vector3 rev_pos = cam_area_pos;
								rev_pos.y = 0;
								rev_pos.normalize();

								if (cc >= 1) {
									// Stereo pair
									float c = rev_pos.x * 0.5 + 0.5;
									output.reverb_vol[0].l = 1.0 - c;
									output.reverb_vol[0].r = c;
								}

								if (cc >= 3) {
									// Center pair + Side pair
									float xl = Vector3(-1, 0, -1).normalized().dot(rev_pos) * 0.5 + 0.5;
									float xr = Vector3(1, 0, -1).normalized().dot(rev_pos) * 0.5 + 0.5;

									output.reverb_vol[1].l = xl;
									output.reverb_vol[1].r = xr;
									output.reverb_vol[2].l = 1.0 - xr;
									output.reverb_vol[2].r = 1.0 - xl;
								}

								if (cc >= 4) {
									// Rear pair
									// FIXME: Not sure what math should be done here
									float c = rev_pos.x * 0.5 + 0.5;
									output.reverb_vol[3].l = 1.0 - c;
									output.reverb_vol[3].r = c;
								}

								for (int i = 0; i < vol_index_max; i++) {

									output.reverb_vol[i] = output.reverb_vol[i].linear_interpolate(center_frame, attenuation);
								}
							} else {
								for (int i = 0; i < vol_index_max; i++) {

									output.reverb_vol[i] = center_frame;
								}
							}

							for (int i = 0; i < vol_index_max; i++) {

								output.reverb_vol[i] = output.vol[i].linear_interpolate(output.reverb_vol[i] * attenuation, uniformity);
								output.reverb_vol[i] *= area_send;
							}

						} else {

							for (int i = 0; i < vol_index_max; i++) {

								output.reverb_vol[i] = output.vol[i] * area_send;
							}
						}
					}
				}

				if (doppler_tracking != DOPPLER_TRACKING_DISABLED) {

					Vector3 camera_velocity = camera->get_doppler_tracked_velocity();

					Vector3 local_velocity = camera->get_global_transform().orthonormalized().basis.xform_inv(linear_velocity - camera_velocity);

					if (local_velocity == Vector3()) {
						output.pitch_scale = 1.0;
					} else {
						float approaching = local_pos.normalized().dot(local_velocity.normalized());
						float velocity = local_velocity.length();
						float speed_of_sound = 343.0;

						output.pitch_scale = speed_of_sound / (speed_of_sound + velocity * approaching);
						output.pitch_scale = CLAMP(output.pitch_scale, (1 / 8.0), 8.0); //avoid crazy stuff
					}

				} else {
					output.pitch_scale = 1.0;
				}

				if (!filled_reverb) {

					for (int i = 0; i < vol_index_max; i++) {

						output.reverb_vol[i] = AudioFrame(0, 0);
					}
				}

				outputs[new_output_count] = output;
				new_output_count++;
				if (new_output_count == MAX_OUTPUTS)
					break;
			}

			output_count = new_output_count;
			output_ready = true;
		}

		//start playing if requested
		if (setplay >= 0.0) {
			setseek = setplay;
			active = true;
			setplay = -1;
			//do not update, this makes it easier to animate (will shut off otherise)
			///_change_notify("playing"); //update property in editor
		}

		//stop playing if no longer active
		if (!active) {
			set_physics_process_internal(false);
			//do not update, this makes it easier to animate (will shut off otherise)
			//_change_notify("playing"); //update property in editor
			emit_signal("finished");
		}
	}
}
예제 #8
0
 virtual void doAction() {
     sound->play(L"glasbk2.wav");
     bool restart = false;
     bool newGame = false;
     Font font(L"laudcn2.ttf", 24);
     Font btnFont(L"laudcn2.ttf", 14);
     Area area;
     area.add(gameArea);
     area.add(new Window(220, 240, 360, 140, L"redpattern.bmp", 6));
     area.add(new Label(&font, 250, 230, 300, 100, Label::ALIGN_CENTER,
                 Label::ALIGN_MIDDLE, 255,255,0, msg(L"loose")));
     OkDlgCommand newGameCmd(&area, newGame);
     area.add(new Button(250, 340, 90, 25, &btnFont, 255,255,0, 
                 L"redpattern.bmp", msg(L"startNew"), &newGameCmd));
     OkDlgCommand restartCmd(&area, restart);
     area.add(new Button(350, 340, 90, 25, &btnFont, 255,255,0, 
                 L"redpattern.bmp", msg(L"tryAgain"), &restartCmd));
     ExitCommand exitCmd(area);
     area.add(new Button(450, 340, 90, 25, &btnFont, 255,255,0, 
                 L"redpattern.bmp", msg(L"exit"), &exitCmd));
     area.run();
     if (restart || newGame) {
         if (newGame)
             game->newGame();
         else
             game->restart();
         gameArea->draw();
         gameArea->updateMouse();
     } else
         gameArea->finishEventLoop();
 };
예제 #9
0
 virtual void doAction() {
     showOptionsWindow(gameArea);
     gameArea->updateMouse();
     gameArea->draw();
 };
예제 #10
0
 virtual void doAction() { 
     res = true; 
     area->finishEventLoop();
 };
예제 #11
0
void ObjectManager::Draw()
{
    // Render state
#if ! defined(CINDER_GLES)
    m_wireframe ? gl::enableWireframe() : gl::disableWireframe();
#endif

//    m_fbo.bindFramebuffer();

    gl::enableVerticalSync();   // TODO: why can't this be set once at setup?
    gl::enableAlphaBlending();
    gl::enableDepthRead();
    gl::enable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    gl::clear(ColorA(178/255.f,178/255.f,178/255.f,1.0f));

    // Draw Player 1
    gl::pushMatrices();
    gl::setViewport(Area(0, 0, g_pApp->getWindowWidth()*getWindow()->getContentScale()/2, g_pApp->getWindowHeight()*getWindow()->getContentScale()));
    gl::setMatrices(m_pPlayer1->m_cam.GetCamera());

    for (auto i = m_objects.begin(); i != m_objects.end(); i++)
    {
        (*i)->Draw();
    }

    if (m_pWorld)
    {
        m_pWorld->Draw();
    }

    m_pPlayer1->Draw();
    if (m_gameState == PLAYING)
    {
        m_pPlayer1->DrawCursor();
    }
    gl::popMatrices();

    // Draw Player 2
    gl::pushMatrices();
    gl::setViewport(Area(g_pApp->getWindowWidth()*getWindow()->getContentScale()/2, 0, g_pApp->getWindowWidth()*getWindow()->getContentScale(), g_pApp->getWindowHeight()*getWindow()->getContentScale()));
    gl::setMatrices(m_pPlayer2->m_cam.GetCamera());

    for (auto i = m_objects.begin(); i != m_objects.end(); i++)
    {
        (*i)->Draw();
    }

    if (m_pWorld)
    {
        m_pWorld->Draw();
    }

    m_pPlayer2->Draw();
    if (m_gameState == PLAYING)
    {
        m_pPlayer2->DrawCursor();
    }
    gl::popMatrices();
/*
    // Render framebuffer
    m_fbo.unbindFramebuffer();
    gl::enableVerticalSync();   // TODO: why can't this be set once at setup?
    gl::enableAlphaBlending();
    gl::enableDepthRead(false);
    gl::enableDepthWrite(false);
    gl::disable(GL_CULL_FACE);

    // Post process shader on FBO
    gl::color(1.f, 1.f, 1.f, 1.f);
    gl::setMatricesWindow(getWindowSize(), false);
    gl::Texture fboTex = m_fbo.getTexture();

    fboTex.enableAndBind();
    m_shader.bind();
    m_shader.uniform("tex0", 0);
    m_shader.uniform("resolution", Vec2f(fboTex.getWidth(), fboTex.getHeight()));
    m_shader.uniform("timer", static_cast<float>(m_playtime));
    m_shader.uniform("resolutionScale", getWindow()->getContentScale());

    gl::drawSolidRect(getWindowBounds());

    m_shader.unbind();
    fboTex.unbind();
    fboTex.disable();
*/
    // Draw game screens
//    gl::pushMatrices();
     gl::color(1,1,1,1);
    Vec2i windowSize = getWindowSize();

    int dim = windowSize.y < windowSize.x ? windowSize.y : windowSize.x;
    float scale = 1.4f;
    dim *= scale;

    float texRatio = 1.f;   // height / width
    int xoffset = 0;
    int yoffset = 0;
    Area bounds;

    switch (m_gameState)
    {
        case TITLE:
            texRatio = 0.5;
            xoffset = (windowSize.x - dim) / 2;
            yoffset = (windowSize.y - (dim*texRatio)) / 2;
            bounds.set(xoffset, yoffset, windowSize.x - xoffset, windowSize.y - yoffset);

            gl::setViewport(Area(0, 0, g_pApp->getWindowWidth()*getWindow()->getContentScale(), g_pApp->getWindowHeight()*getWindow()->getContentScale()));
            gl::setMatricesWindow(windowSize);
            gl::draw(m_titleTex, bounds);
            break;
        case RULES:
            texRatio = 0.5;
            xoffset = (windowSize.x - dim) / 2;
            yoffset = (windowSize.y - (dim*texRatio)) / 2;
            bounds.set(xoffset, yoffset, windowSize.x - xoffset, windowSize.y - yoffset);

            gl::setViewport(Area(0, 0, g_pApp->getWindowWidth()*getWindow()->getContentScale(), g_pApp->getWindowHeight()*getWindow()->getContentScale()));
            gl::setMatricesWindow(windowSize);
            gl::draw(m_rulesTex, bounds);
            break;
        case READY:
            texRatio = 0.5;
            xoffset = (windowSize.x - dim) / 2;
            yoffset = (windowSize.y - (dim*texRatio)) / 2;
            bounds.set(xoffset, yoffset, windowSize.x - xoffset, windowSize.y - yoffset);

            gl::setViewport(Area(0, 0, g_pApp->getWindowWidth()*getWindow()->getContentScale(), g_pApp->getWindowHeight()*getWindow()->getContentScale()));
            gl::setMatricesWindow(windowSize);
            gl::draw(m_readyTex, bounds);
            break;
        case PLAYING:
            break;
        case P1_WINS:
            texRatio = 1;
            xoffset = (windowSize.x - dim*.7f) / 2;
            yoffset = (windowSize.y - (dim*.7f*texRatio)) / 2;
            bounds.set(xoffset, yoffset, windowSize.x - xoffset, windowSize.y - yoffset);

            gl::setViewport(Area(0, 0, g_pApp->getWindowWidth()*getWindow()->getContentScale()/2, g_pApp->getWindowHeight()*getWindow()->getContentScale()));
            gl::setMatricesWindow(windowSize);;
            gl::draw(m_winnerTex, bounds);

            gl::setViewport(Area(g_pApp->getWindowWidth()*getWindow()->getContentScale()/2, 0, g_pApp->getWindowWidth()*getWindow()->getContentScale(), g_pApp->getWindowHeight()*getWindow()->getContentScale()));
            gl::setMatricesWindow(windowSize);;
            gl::draw(m_loserTex, bounds);
            break;
        case P2_WINS:
            texRatio = 1;
            xoffset = (windowSize.x - dim*.7f) / 2;
            yoffset = (windowSize.y - (dim*.7f*texRatio)) / 2;
            bounds.set(xoffset, yoffset, windowSize.x - xoffset, windowSize.y - yoffset);

            gl::setViewport(Area(0, 0, g_pApp->getWindowWidth()*getWindow()->getContentScale()/2, g_pApp->getWindowHeight()*getWindow()->getContentScale()));
            gl::setMatricesWindow(windowSize);;
            gl::draw(m_loserTex, bounds);

            gl::setViewport(Area(g_pApp->getWindowWidth()*getWindow()->getContentScale()/2, 0, g_pApp->getWindowWidth()*getWindow()->getContentScale(), g_pApp->getWindowHeight()*getWindow()->getContentScale()));
            gl::setMatricesWindow(windowSize);;
            gl::draw(m_winnerTex, bounds);
            break;
        case CREDITS:
            texRatio = 0.5;
            xoffset = (windowSize.x - dim) / 2;
            yoffset = (windowSize.y - (dim*texRatio)) / 2;
            bounds.set(xoffset, yoffset, windowSize.x - xoffset, windowSize.y - yoffset);

            gl::setViewport(Area(0, 0, g_pApp->getWindowWidth()*getWindow()->getContentScale(), g_pApp->getWindowHeight()*getWindow()->getContentScale()));
            gl::setMatricesWindow(windowSize);
            gl::draw(m_creditsTex, bounds);
            break;
        default:
            break;
    }
//    gl::pushMatrices();


#if ! defined(CINDER_GLES)
    gl::disableWireframe();
#endif

    // Draw statistics
    if (m_displayStats)
    {
        g_pStats->display();
    }

    // Draw gui
    if (m_displayGui)
    {
//        g_pGui->draw();
    }
}
  bool OptimizeAreaWayIdsGenerator::ScanAreaIds(const ImportParameter& parameter,
                                                Progress& progress,
                                                const TypeConfig& typeConfig,
                                                NodeUseMap& nodeUseMap)
  {
    FileScanner scanner;
    uint32_t    dataCount=0;

    progress.SetAction("Scanning ids from 'areas.tmp'");

    if (!scanner.Open(AppendFileToDir(parameter.GetDestinationDirectory(),
                                      "areas.tmp"),
                      FileScanner::Sequential,
                      parameter.GetAreaDataMemoryMaped())) {
      progress.Error(std::string("Cannot open '")+scanner.GetFilename()+"'");
      return false;
    }

    if (!scanner.Read(dataCount)) {
      progress.Error("Error while reading number of data entries in file");
      return false;
    }

    for (size_t current=1; current<=dataCount; current++) {
      uint8_t type;
      Id      id;
      Area    data;

      progress.SetProgress(current,dataCount);

      if (!scanner.Read(type) ||
          !scanner.Read(id) ||
          !data.Read(typeConfig,
                     scanner)) {
        progress.Error(std::string("Error while reading data entry ")+
                       NumberToString(current)+" of "+
                       NumberToString(dataCount)+
                       " in file '"+
                       scanner.GetFilename()+"'");

        return false;
      }

      for (const auto& ring: data.rings) {
        std::unordered_set<Id> nodeIds;

        if (!ring.GetType()->CanRoute()) {
          continue;
        }

        for (const auto id: ring.ids) {
          if (nodeIds.find(id)==nodeIds.end()) {
            nodeUseMap.SetNodeUsed(id);

            nodeIds.insert(id);
          }
        }
      }
    }

    if (!scanner.Close()) {
      progress.Error(std::string("Error while closing file '")+
                     scanner.GetFilename()+"'");
      return false;
    }

    return true;
  }
  bool OptimizeAreaWayIdsGenerator::CopyAreas(const ImportParameter& parameter,
                                              Progress& progress,
                                              const TypeConfig& typeConfig,
                                              NodeUseMap& nodeUseMap)
  {
    FileScanner scanner;
    FileWriter  writer;
    uint32_t    areaCount=0;

    if (!writer.Open(AppendFileToDir(parameter.GetDestinationDirectory(),
                                     "areas2.tmp"))) {
      progress.Error(std::string("Cannot create '")+writer.GetFilename()+"'");
      return false;
    }

    writer.Write(areaCount);

    progress.SetAction("Copy data from 'areas.tmp' to 'areas2.tmp'");

    if (!scanner.Open(AppendFileToDir(parameter.GetDestinationDirectory(),
                                      "areas.tmp"),
                      FileScanner::Sequential,
                      parameter.GetAreaDataMemoryMaped())) {
      progress.Error(std::string("Cannot open '")+scanner.GetFilename()+"'");
      return false;
    }

    if (!scanner.Read(areaCount)) {
      progress.Error("Error while reading number of data entries in file");
      return false;
    }

    for (size_t current=1; current<=areaCount; current++) {
      uint8_t type;
      Id      id;
      Area    data;

      progress.SetProgress(current,areaCount);

      if (!scanner.Read(type) ||
          !scanner.Read(id) ||
          !data.Read(typeConfig,
                     scanner)) {
        progress.Error(std::string("Error while reading data entry ")+
                       NumberToString(current)+" of "+
                       NumberToString(areaCount)+
                       " in file '"+
                       scanner.GetFilename()+"'");

        return false;
      }

      for (auto& ring : data.rings) {
        std::unordered_set<Id> nodeIds;

        for (auto& id : ring.ids) {
          if (!nodeUseMap.IsNodeUsedAtLeastTwice(id)) {
            id=0;
          }
        }
      }

      if (!writer.Write(type) ||
          !writer.Write(id) ||
          !data.Write(typeConfig,
                      writer)) {
        progress.Error(std::string("Error while writing data entry to file '")+
                       writer.GetFilename()+"'");

        return false;
      }
    }

    if (!scanner.Close()) {
      progress.Error(std::string("Error while closing file '")+
                     scanner.GetFilename()+"'");
      return false;
    }

    if (!writer.SetPos(0)) {
      return false;
    }

    if (!writer.Write(areaCount)) {
      return false;
    }

    if (!writer.Close()) {
      progress.Error(std::string("Error while closing file '")+
                     writer.GetFilename()+"'");
      return false;
    }

    return true;
  }
예제 #14
0
Area* World::move(Player *player,
                  int clip_x, int clip_y, int clip_w, int clip_h)
{
    Area *result = 0;

    if (!player->is_morphing()) {
        result = player->get_warp();
    }

    player->move(m_map);

    int window_width = clip_w - clip_x;
    if (m_lock_x) {
        m_map->set_x(m_lock_x, window_width);
    }
    else {
        int map_x = player->get_x() - window_width / 2 + m_offset_x;
        if (map_x < 0) {
            map_x = 0;
        }
        m_map->set_x(map_x, window_width);
    }

    int window_height = clip_h - clip_y;
    if (m_lock_y) {
        m_map->set_y(m_lock_y, window_height);
    }
    else {
        int map_y = player->get_y() - window_height / 2 + m_offset_y;
        if (map_y < 0) {
            map_y = 0;
        }
        m_map->set_y(map_y, window_height);
    }

    std::vector<Object*> perished;

    for (std::list<Object*>::iterator it = m_objects.begin();
         it != m_objects.end();
         ++it) {
        Object *object = *it;

        if (object->get_visible(m_map, clip_x, clip_y, clip_w, clip_h)) {
            Object::Type object_type = object->get_type();

            // Handle area objects
            if (object_type == Object::TypeArea) {
                Area *area = (Area *) object;

                if (area->is_over(player)) {

                    if (area->is_locked()) {

                        // Check if the player has the key
                        Status *status = m_db->get_status();
                        Item *item = status->check_item(area->get_data());
                        if (item) {
                            if (area->unlock(this, item)) {
                                status->remove_item(item);
                            }
                        }
                    }
                    else {
                        area->move(m_map);

                        if (area->is_open()) {
                            result = area;
                        }
                    }
                }
            }

            // Handle monster object
            else if (object_type == Object::TypeMonster) {
                Monster *monster = (Monster *) object;

                monster->move(m_map);
                monster->set_reference(player->get_front(), player->get_y());
                if (player->check_collision(monster) ||
                    monster->attack_object(player)) {
                    if (!monster->get_invisible()) {
                        player->set_hit(monster, m_db->get_status());
                    }
                }
                if (player->attack_object(monster)) {
                    monster->set_hit(player, m_db->get_status());
                }
                if (monster->get_action() == Actor::HitPerished) {
                    perished.push_back(monster);
                }
            }

            // Handle item objects
            else if (object_type == Object::TypeItem) {
                Item *item = (Item *) object;

                item->move(m_map);

                // Check if player picked up item
                if (player->check_collision(item)) {
                    Status *status = m_db->get_status();
                    status->aquire_item(item);
                    item->aquire(this);
                    item->set_reused(true);
                    perished.push_back(item);
                }
            }

            // Handle collectable objects
            else if (object_type == Object::TypeCollectable) {
                Collectable *collectable = (Collectable *) object;

                collectable->move(m_map);

                // Check if player picked up the collectable
                if (player->check_collision(collectable)) {
                    Status *status = m_db->get_status();
                    status->aquire_collectable(collectable);
                    perished.push_back(collectable);
                }
            }

            // Handle curse objects
            else if (object_type == Object::TypeCurse) {
                Curse *curse = (Curse *) object;

                curse->move(m_map);
                if (player->check_collision(curse)) {
                    player->set_morph(new Morph("human_to_salamander.xml",
                                                m_media,
                                                player->get_x(),
                                                player->get_y(),
                                                player->get_dir()));
                    player->set_warp(new Area(curse));
                    perished.push_back(curse);
                }
            }

            // Handle chest objects
            else if (object_type == Object::TypeChest) {
                Chest *chest = (Chest *) object;
                if (chest->is_open(player)) {
                    Object *released_object = chest->release_object();
                    if (released_object) {
                        released_object->set_x(chest->get_x());
                        released_object->set_y(chest->get_y());
                        released_object->set_reference(player->get_front(),
                                                       player->get_y());
                        m_objects.push_back(released_object);
                    }
                }
            }
        }
    }

    // Remove all perished objects
    for (int i = 0; i < perished.size(); i++) {

        // If monster drop object
        if (perished[i]->get_type() == Object::TypeMonster) {
            Monster *monster = (Monster *) perished[i];
            Object *released_object = monster->release_object();
            if (released_object) {
                released_object->set_x(monster->get_x());
                released_object->set_y(monster->get_y());
                released_object->set_reference(player->get_front(),
                                               player->get_y());
                m_objects.push_back(released_object);
            }
        }
        m_objects.remove(perished[i]);

        if (!perished[i]->get_reused()) {
            delete perished[i];
        }
    }

    return result;
}