File size: 5,150 Bytes
80bcac8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import { useCallback, useRef, useEffect } from 'react'
import { useAppStore } from '@/store'
import { convolutionSteps, convolveImage } from '@/lib/convolution/engine'
import type { PaddingMode, ConvolutionStep } from '@/types'

export function useConvolution() {
  const {
    originalImageData,
    selectedKernel,
    customKernelMatrix,
    customKernelNormalize,
    settings,
    convolution,
    startConvolution,
    pauseConvolution,
    resumeConvolution,
    stopConvolution,
    updateConvolutionStep,
    updateConvolutionProgress,
    completeConvolution,
    setConvolutionError,
    resetConvolution,
  } = useAppStore()

  const animationRef = useRef<number | null>(null)
  const generatorRef = useRef<Generator<ConvolutionStep> | null>(null)
  const isPausedRef = useRef(false)
  const stepModeRef = useRef(false)

  const kernel = selectedKernel?.matrix ?? customKernelMatrix
  const normalize = selectedKernel?.normalize ?? customKernelNormalize
  const padding = settings.padding

  const runConvolution = useCallback(async () => {
    if (!originalImageData || !kernel) return

    try {
      startConvolution()

      const extendedImage = {
        data: originalImageData.data,
        width: originalImageData.width,
        height: originalImageData.height,
        channels: 4,
      }

      const gen = convolutionSteps(extendedImage, kernel, padding, normalize, (progress) => {
        const totalPixels = originalImageData.width * originalImageData.height * 4
        const processedPixels = Math.round(progress * totalPixels)
        const elapsedTime = Date.now() - convolution.startTime
        updateConvolutionProgress(progress, processedPixels, elapsedTime)
      })

      generatorRef.current = gen

      const processBatch = () => {
        if (isPausedRef.current || stepModeRef.current) {
          animationRef.current = requestAnimationFrame(processBatch)
          return
        }

        const batchSize = Math.max(1, Math.floor(1000 * settings.animationSpeed))
        let lastStep: ConvolutionStep | null = null

        for (let i = 0; i < batchSize; i++) {
          const result = gen.next()
          if (result.done) {
            if (lastStep && lastStep.x === -1) {
              // Final step with output image
              const outputImageData = new ImageData(
                new Uint8ClampedArray(originalImageData.data.length),
                originalImageData.width,
                originalImageData.height
              )
              // We need to reconstruct from the generator's final output
              // For now, use the direct convolution
              const output = convolveImage(originalImageData, kernel, padding, normalize)
              completeConvolution(output)
            }
            return
          }
          lastStep = result.value
          updateConvolutionStep(result.value)
        }

        animationRef.current = requestAnimationFrame(processBatch)
      }

      animationRef.current = requestAnimationFrame(processBatch)
    } catch (error) {
      setConvolutionError(error instanceof Error ? error.message : 'Convolution failed')
    }
  }, [
    originalImageData,
    kernel,
    normalize,
    padding,
    settings.animationSpeed,
    convolution.startTime,
    startConvolution,
    updateConvolutionStep,
    updateConvolutionProgress,
    completeConvolution,
    setConvolutionError,
  ])

  const pause = useCallback(() => {
    isPausedRef.current = true
    pauseConvolution()
  }, [pauseConvolution])

  const resume = useCallback(() => {
    isPausedRef.current = false
    resumeConvolution()
  }, [resumeConvolution])

  const stop = useCallback(() => {
    if (animationRef.current) {
      cancelAnimationFrame(animationRef.current)
      animationRef.current = null
    }
    isPausedRef.current = false
    stepModeRef.current = false
    generatorRef.current = null
    stopConvolution()
  }, [stopConvolution])

  const step = useCallback(() => {
    if (!generatorRef.current) return
    stepModeRef.current = true
    const result = generatorRef.current.next()
    if (!result.done) {
      updateConvolutionStep(result.value)
    } else if (result.value && result.value.x === -1) {
      const output = convolveImage(originalImageData!, kernel, padding, normalize)
      completeConvolution(output)
    }
  }, [originalImageData, kernel, padding, normalize, updateConvolutionStep, completeConvolution])

  const reset = useCallback(() => {
    stop()
    resetConvolution()
  }, [stop, resetConvolution])

  const toggleStepMode = useCallback((enabled: boolean) => {
    stepModeRef.current = enabled
  }, [])

  useEffect(() => {
    return () => {
      if (animationRef.current) {
        cancelAnimationFrame(animationRef.current)
      }
    }
  }, [])

  return {
    convolution,
    runConvolution,
    pause,
    resume,
    stop,
    step,
    reset,
    toggleStepMode,
    isRunning: convolution.status === 'running',
    isPaused: convolution.status === 'paused',
    isCompleted: convolution.status === 'completed',
    canRun: !!originalImageData && !!kernel && convolution.status !== 'running',
  }
}