<template>
    <TresMesh ref="plane">
        <TresPlaneGeometry :args="[1, 1]" />
        <TresShaderMaterial v-bind="materialProps" />
    </TresMesh>
</template>

<script setup>
import fragShader from '@/libs/glsl/noise-image/frag.glsl'
import vertShader from '@/libs/glsl/noise-image/vert.glsl'
import { useTexture } from '@tresjs/cientos'
import { useLoop } from '@tresjs/core'
import { useWindowSize } from '@vueuse/core'
import useSmoothMouse from '@/composables/useSmoothMouse'
import { computed, shallowRef } from 'vue'

const { width, height } = useWindowSize()
useSmoothMouse({
  normalize: true,
  onUpdate: ({ sx, sy }) => {
    plane.value.material.uniforms.u_mouse.value = [sx, 1 - sy]
  },
})

const plane = shallowRef()

const { state: texture } = await useTexture(['/drops/noise-shader/fill-1.jpg'])
const textureResolution = computed(() => {
    const width = texture.value.source?.data.naturalWidth
    const height = texture.value.source?.data.naturalHeight

    return [width, height]
})

const materialProps = {
    fragmentShader: fragShader,
    vertexShader: vertShader,
    uniforms: {
        u_time: { value: 0 },
        u_resolution: { value: [width.value, height.value] },
        u_grid_size: { value: 120 },
        u_texture: { value: texture.value },
        u_texture_resolution: { value: textureResolution.value },
        u_mouse: { value: [0, 0] },
    },
}

const { onRender } = useLoop()
onRender(({ elapsed }) => {
  plane.value.material.uniforms.u_time.value = elapsed / 1000
  plane.value.material.uniforms.u_resolution.value = [
      width.value,
      height.value,
  ]
  plane.value.material.uniforms.u_texture_resolution.value =
      textureResolution.value
})
</script>
