2020-12-01 21:15:19 +01:00
|
|
|
# Copyright 2020 Google LLC
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# https://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2018-12-10 15:52:34 +01:00
|
|
|
import time
|
2018-12-05 02:52:31 +01:00
|
|
|
|
2024-02-27 07:58:25 +01:00
|
|
|
import compat
|
2018-12-05 02:52:31 +01:00
|
|
|
|
2024-03-01 17:13:18 +01:00
|
|
|
from typing import Generator
|
2024-02-27 08:05:22 +01:00
|
|
|
|
2024-03-01 17:13:18 +01:00
|
|
|
|
|
|
|
def delay(secs: float) -> Generator[None, None, None]:
|
2024-02-27 07:58:25 +01:00
|
|
|
end = compat.monotonic() + secs
|
|
|
|
while compat.monotonic() < end:
|
2018-12-05 02:52:31 +01:00
|
|
|
yield None
|
|
|
|
|
|
|
|
|
2024-03-01 17:13:18 +01:00
|
|
|
def fps(fps: float) -> Generator[None, None, None]:
|
2018-12-10 16:33:33 +01:00
|
|
|
yield None
|
2018-12-29 16:28:55 +01:00
|
|
|
dt = 1 / fps
|
2024-02-27 07:58:25 +01:00
|
|
|
until = compat.monotonic() + dt
|
2018-12-05 02:52:31 +01:00
|
|
|
while True:
|
2024-02-27 07:58:25 +01:00
|
|
|
remain = until - compat.monotonic()
|
2018-12-10 15:52:34 +01:00
|
|
|
if remain > 0:
|
2024-02-27 07:58:25 +01:00
|
|
|
compat.sleep(remain)
|
2018-12-10 16:33:33 +01:00
|
|
|
until += dt
|
|
|
|
if remain < -dt:
|
|
|
|
# Catch up a bit
|
|
|
|
until += -remain / 3
|
2018-12-05 02:52:31 +01:00
|
|
|
yield None
|
|
|
|
|
|
|
|
|
2024-03-01 17:13:18 +01:00
|
|
|
def wait(stop_ms: int) -> Generator[int, None, None]:
|
|
|
|
"""Waits for stop_ms to pass, yielding how many ms have passed so far."""
|
2024-02-27 07:58:25 +01:00
|
|
|
start = compat.monotonic()
|
2018-12-29 16:28:55 +01:00
|
|
|
while True:
|
2024-02-27 07:58:25 +01:00
|
|
|
elapsed = int((compat.monotonic() - start) * 1000)
|
2024-03-01 17:13:18 +01:00
|
|
|
elapsed = min(stop_ms, elapsed)
|
2018-12-29 16:28:55 +01:00
|
|
|
yield elapsed
|
2024-03-01 17:13:18 +01:00
|
|
|
if elapsed >= stop_ms:
|
2018-12-29 16:28:55 +01:00
|
|
|
break
|