<script setup lang="ts">
import {
    PCFSoftShadowMap,
    CineonToneMapping,
    PMREMGenerator,
    Vector3,
} from 'three';
import { GainMapLoader, } from '@monogrid/gainmap-js'
import { useLoop } from '@tresjs/core';
const { scene, renderer, camera } = useTresContext()
const {onBeforeRender} = useLoop()

renderer.value.toneMapping = CineonToneMapping
renderer.value.toneMappingExposure = 1

renderer.value.shadowMap.enabled = true
renderer.value.shadowMap.type = PCFSoftShadowMap

const pmremGenerator = new PMREMGenerator(renderer.value);
pmremGenerator.compileEquirectangularShader();
onMounted(async () => {
    const loader = new GainMapLoader(renderer.value)
    const result = await loader.loadAsync([
        'hdrmaps/hdr.webp',
        'hdrmaps/hdr-gainmap.webp',
        'hdrmaps/hdr.json',
    ])
    if (renderer.value && camera.value) {
        renderer.value.render(scene.value, camera.value)
    }
    const exrCubeRenderTarget = pmremGenerator.fromEquirectangular(result.renderTarget.texture);
    const newEnvMap = exrCubeRenderTarget ? exrCubeRenderTarget.texture : null;

    scene.value.environment = newEnvMap
    scene.value.environmentIntensity = 1.25
    scene.value.environmentRotation.z = 0.25
    result.renderTarget.texture.dispose();
})
onBeforeRender(()=>{
    if(camera.value) {
        const cameraDirection = new Vector3()
        camera.value.getWorldDirection(cameraDirection);
        const angle = Math.atan2(cameraDirection.z, cameraDirection.x);
        scene.value.environmentRotation.z = angle + 0.25
    }
})
</script>
<template></template>