59 lines
1.9 KiB
TypeScript
59 lines
1.9 KiB
TypeScript
import { ref, computed } from 'vue'
|
|
|
|
type TimeOfDay =
|
|
| 'day'
|
|
| 'night'
|
|
| 'morning0'
|
|
| 'morning1'
|
|
| 'morning2'
|
|
| 'evening0'
|
|
| 'evening1'
|
|
| 'evening2'
|
|
|
|
export function calcTimeOfDay(tick: number): TimeOfDay {
|
|
if (tick >= 900 || tick < 80) return 'night'
|
|
if (tick >= 80 && tick < 120) return 'morning0'
|
|
if (tick >= 120 && tick < 150) return 'morning1'
|
|
if (tick >= 150 && tick < 240) return 'morning2'
|
|
if (tick >= 700 && tick < 800) return 'evening0'
|
|
if (tick >= 800 && tick < 850) return 'evening1'
|
|
if (tick >= 850 && tick < 900) return 'evening2'
|
|
return 'day'
|
|
}
|
|
|
|
export function renderClock(tick: number): string {
|
|
const t = tick * 86.4 // 1000 ticks to 86400 seconds (per day)
|
|
const h = ~~(t / 3600.0)
|
|
const m = ~~((t / 3600.0 - h) * 60.0)
|
|
return `${(h + 2) % 24}:${m < 10 ? '0' : ''}${m}`
|
|
}
|
|
|
|
function calcProgress(tick: number, start: number, end: number, span: number): number {
|
|
return (tick - start) / (end - start) * span
|
|
}
|
|
|
|
// calculates the suns angle from -90 (top, at noon), to 0 (at midnight)
|
|
export function calcSunAngle(tick: number): number {
|
|
// night time: -10 degrees fixed
|
|
if (tick >= 900 || tick < 80) return -10
|
|
// sunrise: gradually move from -10 to -90, by mapping 80 -> 240 to -10 -> -90
|
|
if (tick >= 80 && tick < 240) return -10 - calcProgress(tick, 80, 240, 80)
|
|
// sundawn: gradually move from -90 to -10, by mapping 700 -> 900 to -90 -> -10
|
|
if (tick >= 700 && tick < 900) return -90 + calcProgress(tick, 700, 900, 80)
|
|
// day time: -90 degrees fixed
|
|
return -90
|
|
}
|
|
|
|
export default function useTime() {
|
|
// the day is split in 1000 parts, so we start in the morning
|
|
const time = ref(240)
|
|
|
|
function updateTime() {
|
|
time.value = (time.value + 0.1) % 1000
|
|
}
|
|
|
|
const timeOfDay = computed(() => calcTimeOfDay(time.value))
|
|
const clock = computed(() => renderClock(time.value))
|
|
|
|
return { time, updateTime, timeOfDay, clock }
|
|
}
|