Browse Source

Add optional wait timeout parameter to love.event.pump.

Deprecate love.event.wait.
Sasha Szpakowski 10 months ago
parent
commit
88137d1b65

+ 1 - 1
src/modules/event/Event.h

@@ -61,7 +61,7 @@ public:
 	bool poll(Message *&msg);
 	virtual void clear();
 
-	virtual void pump() = 0;
+	virtual void pump(float waitTimeout = 0.0f) = 0;
 	virtual Message *wait() = 0;
 
 protected:

+ 17 - 6
src/modules/event/sdl/Event.cpp

@@ -119,19 +119,30 @@ Event::~Event()
 	SDL_QuitSubSystem(SDL_INIT_EVENTS);
 }
 
-void Event::pump()
+void Event::pump(float waitTimeout)
 {
 	exceptionIfInRenderPass("love.event.pump");
 
-	SDL_Event e;
+	int waitTimeoutMS = 0;
+	if (isinf(waitTimeout) || waitTimeout < 0.0f)
+		waitTimeoutMS = -1; // Wait forever.
+	else if (waitTimeout > 0.0f)
+		waitTimeoutMS = (int)std::min<int64>(LOVE_INT32_MAX, 1000LL * waitTimeout);
 
-	while (SDL_PollEvent(&e))
+	// Wait for the first event, if requested.
+	SDL_Event e;
+	if (SDL_WaitEventTimeout(&e, waitTimeoutMS))
 	{
-		Message *msg = convert(e);
+		StrongRef<Message> msg(convert(e), Acquire::NORETAIN);
 		if (msg)
-		{
 			push(msg);
-			msg->release();
+
+		// Fetch any extra events that came in during WaitEvent.
+		while (SDL_PollEvent(&e))
+		{
+			msg.set(convert(e), Acquire::NORETAIN);
+			if (msg)
+				push(msg);
 		}
 	}
 }

+ 4 - 8
src/modules/event/sdl/Event.h

@@ -47,19 +47,15 @@ public:
 	 * from devices and places it on the event queue. Normally not needed if you poll
 	 * for events.
 	 **/
-	void pump();
+	void pump(float waitTimeout = 0.0f) override;
 
-	/**
-	 * Waits for the next event (indefinitely). Useful for creating games where
-	 * the screen and game state only needs updating when the user interacts with
-	 * the window.
-	 **/
-	Message *wait();
+	// Deprecated.
+	Message *wait() override;
 
 	/**
 	 * Clears the event queue.
 	 */
-	void clear();
+	void clear() override;
 
 private:
 

+ 4 - 1
src/modules/event/wrap_Event.cpp

@@ -65,12 +65,15 @@ static int w_poll_i(lua_State *L)
 
 int w_pump(lua_State *L)
 {
-	luax_catchexcept(L, [&]() { instance()->pump(); });
+	float waitTimeout = (float)luaL_optnumber(L, 1, 0.0f);
+	luax_catchexcept(L, [&]() { instance()->pump(waitTimeout); });
 	return 0;
 }
 
 int w_wait(lua_State *L)
 {
+	luax_markdeprecated(L, 1, "love.event.wait", API_FUNCTION, DEPRECATED_REPLACED, "waitTimeout parameter in love.event.pump");
+
 	Message *m = nullptr;
 	luax_catchexcept(L, [&]() { m = instance()->wait(); });
 	if (m != nullptr)