2023-09-14 10:47:55 +10:00
|
|
|
import { useLayoutEffect } from 'react'
|
|
|
|
import { _executor } from '../lang/executor'
|
|
|
|
import { useStore } from '../useStore'
|
|
|
|
import { EngineCommandManager } from '../lang/std/engineConnection'
|
|
|
|
|
|
|
|
export function useSetupEngineManager(
|
|
|
|
streamRef: React.RefObject<HTMLDivElement>,
|
|
|
|
token?: string
|
|
|
|
) {
|
|
|
|
const {
|
|
|
|
setEngineCommandManager,
|
|
|
|
setMediaStream,
|
|
|
|
setIsStreamReady,
|
|
|
|
setStreamDimensions,
|
2023-09-15 04:35:48 -07:00
|
|
|
executeCode,
|
2023-09-14 10:47:55 +10:00
|
|
|
} = useStore((s) => ({
|
|
|
|
setEngineCommandManager: s.setEngineCommandManager,
|
|
|
|
setMediaStream: s.setMediaStream,
|
|
|
|
setIsStreamReady: s.setIsStreamReady,
|
|
|
|
setStreamDimensions: s.setStreamDimensions,
|
2023-09-15 04:35:48 -07:00
|
|
|
executeCode: s.executeCode,
|
2023-09-14 10:47:55 +10:00
|
|
|
}))
|
|
|
|
|
|
|
|
const streamWidth = streamRef?.current?.offsetWidth
|
|
|
|
const streamHeight = streamRef?.current?.offsetHeight
|
|
|
|
|
|
|
|
const width = streamWidth ? streamWidth : 0
|
|
|
|
const quadWidth = Math.round(width / 4) * 4
|
|
|
|
const height = streamHeight ? streamHeight : 0
|
|
|
|
const quadHeight = Math.round(height / 4) * 4
|
|
|
|
|
|
|
|
useLayoutEffect(() => {
|
|
|
|
setStreamDimensions({
|
|
|
|
streamWidth: quadWidth,
|
|
|
|
streamHeight: quadHeight,
|
|
|
|
})
|
|
|
|
if (!width || !height) return
|
|
|
|
const eng = new EngineCommandManager({
|
|
|
|
setMediaStream,
|
|
|
|
setIsStreamReady,
|
|
|
|
width: quadWidth,
|
|
|
|
height: quadHeight,
|
|
|
|
token,
|
|
|
|
})
|
|
|
|
setEngineCommandManager(eng)
|
2023-09-15 04:35:48 -07:00
|
|
|
eng.waitForReady.then(() => {
|
|
|
|
executeCode()
|
|
|
|
})
|
2023-09-14 10:47:55 +10:00
|
|
|
return () => {
|
|
|
|
eng?.tearDown()
|
|
|
|
}
|
|
|
|
}, [quadWidth, quadHeight])
|
|
|
|
}
|