Code Sketch


yoi
By: Mhalsakant School
Category: Programming
// ============================================
// TURTLE IMAGE TO KOJO CODE GENERATOR V3
// CLIPBOARD EDITION - FIXED
// ============================================

import java.awt.Toolkit
import java.awt.Color
import java.awt.BorderLayout
import java.awt.Font
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.StringSelection
import java.awt.image.BufferedImage

import javax.swing._
import javax.swing.filechooser.FileNameExtensionFilter

// ============================================
// SETTINGS
// ============================================

val MAX_SIDE = 90
val CONTRAST = 1.20

// ============================================
// IMAGE PROCESSOR
// ============================================

try {

    val clipboard =
        Toolkit.getDefaultToolkit.getSystemClipboard

    val contents =
        clipboard.getContents(null)

    if (
        contents == null ||
        !contents.isDataFlavorSupported(DataFlavor.imageFlavor)
    ) {

        JOptionPane.showMessageDialog(
            null,
            "IMAGE NOT FOUND!\n\n" +
            "Open your photo in Paint.\n" +
            "Press CTRL + A.\n" +
            "Press CTRL + C.\n" +
            "Then run this code again."
        )

    } else {

        val original =
            contents.getTransferData(DataFlavor.imageFlavor)
                .asInstanceOf[java.awt.Image]

        val imageIcon = new ImageIcon(original)

        val iw = imageIcon.getIconWidth
        val ih = imageIcon.getIconHeight

        if (iw <= 0 || ih <= 0) {
            throw new Exception("Invalid image!")
        }

        // ====================================
        // RESIZE
        // ====================================

        val ratio = math.min(
            1.0,
            MAX_SIDE.toDouble / math.max(iw, ih)
        )

        val w = math.max(1, (iw * ratio).toInt)
        val h = math.max(1, (ih * ratio).toInt)

        val img = new BufferedImage(
            w,
            h,
            BufferedImage.TYPE_INT_RGB
        )

        val graphics = img.createGraphics()

        graphics.setColor(Color.WHITE)
        graphics.fillRect(0, 0, w, h)

        graphics.setRenderingHint(
            java.awt.RenderingHints.KEY_INTERPOLATION,
            java.awt.RenderingHints.VALUE_INTERPOLATION_BICUBIC
        )

        graphics.drawImage(
            imageIcon.getImage,
            0, 0, w, h,
            null
        )

        graphics.dispose()

        // ====================================
        // GRAYSCALE
        // ====================================

        val gray = Array.ofDim[Double](h, w)

        for (y <- 0 until h) {

            for (x <- 0 until w) {

                val rgb = img.getRGB(x, y)

                val r = (rgb >> 16) & 255
                val g = (rgb >> 8) & 255
                val b = rgb & 255

                val value =
                    0.299 * r +
                    0.587 * g +
                    0.114 * b

                gray(y)(x) = math.max(
                    0.0,
                    math.min(
                        255.0,
                        (value - 128.0) * CONTRAST + 128.0
                    )
                )
            }
        }

        // ====================================
        // FLOYD STEINBERG DITHERING
        // ====================================

        val work = Array.tabulate(h, w) {
            (y, x) => gray(y)(x)
        }

        val dark = Array.ofDim[Boolean](h, w)

        def spread(
            x: Int,
            y: Int,
            error: Double,
            factor: Double
        ): Unit = {

            if (
                x >= 0 && x < w &&
                y >= 0 && y < h
            ) {

                work(y)(x) = math.max(
                    0.0,
                    math.min(
                        255.0,
                        work(y)(x) + error * factor
                    )
                )
            }
        }

        for (y <- 0 until h) {

            for (x <- 0 until w) {

                val oldValue = work(y)(x)

                val newValue =
                    if (oldValue < 128) 0.0
                    else 255.0

                dark(y)(x) = newValue == 0.0

                val error = oldValue - newValue

                spread(
                    x + 1, y, error, 7.0 / 16.0
                )

                spread(
                    x - 1, y + 1, error, 3.0 / 16.0
                )

                spread(
                    x, y + 1, error, 5.0 / 16.0
                )

                spread(
                    x + 1, y + 1, error, 1.0 / 16.0
                )
            }
        }

        // ====================================
        // GENERATE SOURCE CODE
        // ====================================

        val code = new StringBuilder

        def emit(s: String): Unit = {
            code.append(s).append("\n")
        }

        def number(n: Double): String = {
            java.lang.Double.toString(n)
        }

        emit("// ====================================")
        emit("// TURTLE GENERATED IMAGE DRAWING")
        emit("// Automatically generated Kojo source")
        emit("// ====================================")

        emit("")

        emit("cleari()")
        emit("setBackground(white)")
        emit("setPenColor(black)")
        emit("setPenThickness(1.0)")
        emit("setSpeed(slow)")
        emit("visible()")

        emit("")

        emit("val cb = canvasBounds")

        emit(
            "val aspect = " +
            number(w.toDouble / h.toDouble)
        )

        emit("val maxW = cb.width * 0.82")
        emit("val maxH = cb.height * 0.82")

        emit("val drawW = math.min(maxW, maxH * aspect)")
        emit("val drawH = drawW / aspect")

        emit("val left = cb.x + (cb.width - drawW) / 2.0")
        emit("val bottom = cb.y + (cb.height - drawH) / 2.0")

        emit("")

        emit(
            "def drawStroke(x1: Double, y: Double, x2: Double): Unit = {"
        )

        emit("    penUp()")

        emit(
            "    setPosition(left + x1 * drawW, bottom + (1.0-y) * drawH)"
        )

        emit("    penDown()")

        emit(
            "    lineTo(left + x2 * drawW, bottom + (1.0-y) * drawH)"
        )

        emit("    penUp()")

        emit("}")

        emit("")

        emit("// IMAGE DRAWING COMMANDS")
        emit("")

        var strokes = 0

        for (y <- 0 until h) {

            var x = 0

            while (x < w) {

                if (dark(y)(x)) {

                    val start = x

                    while (
                        x < w &&
                        dark(y)(x)
                    ) {
                        x += 1
                    }

                    val end = x

                    val x1 = start.toDouble / w
                    val x2 = end.toDouble / w
                    val yy = (y + 0.5) / h

                    emit(
                        "drawStroke(" +
                        number(x1) + ", " +
                        number(yy) + ", " +
                        number(x2) + ")"
                    )

                    strokes += 1

                } else {

                    x += 1
                }
            }
        }

        emit("")
        emit("penUp()")
        emit("invisible()")
        emit("println(\"DRAWING COMPLETED!\")")

        val generatedCode = code.toString

        // ====================================
        // CREATE CODE WINDOW
        // ====================================

        SwingUtilities.invokeLater(
            new Runnable {

                override def run(): Unit = {

                    val frame = new JFrame(
                        "TURTLE IMAGE - GENERATED CODE"
                    )

                    // FIXED CLOSE OPERATION
                    frame.setDefaultCloseOperation(
                        WindowConstants.DISPOSE_ON_CLOSE
                    )

                    val area = new JTextArea(
                        generatedCode
                    )

                    area.setFont(
                        new Font(
                            "Consolas",
                            Font.PLAIN,
                            12
                        )
                    )

                    area.setTabSize(4)
                    area.setEditable(false)

                    val scroll = new JScrollPane(area)

                    val copyButton = new JButton(
                        "COPY GENERATED CODE"
                    )

                    copyButton.addActionListener(
                        new java.awt.event.ActionListener {

                            override def actionPerformed(
                                e: java.awt.event.ActionEvent
                            ): Unit = {

                                val selection =
                                    new StringSelection(
                                        area.getText
                                    )

                                Toolkit.getDefaultToolkit
                                    .getSystemClipboard
                                    .setContents(
                                        selection,
                                        null
                                    )

                                JOptionPane.showMessageDialog(
                                    frame,
                                    "CODE COPIED SUCCESSFULLY!\n\n" +
                                    "Open new Kojo script.\n" +
                                    "Press CTRL + V."
                                )
                            }
                        }
                    )

                    val bottomPanel = new JPanel(
                        new BorderLayout()
                    )

                    bottomPanel.add(
                        copyButton,
                        BorderLayout.CENTER
                    )

                    frame.setLayout(
                        new BorderLayout()
                    )

                    frame.add(
                        scroll,
                        BorderLayout.CENTER
                    )

                    frame.add(
                        bottomPanel,
                        BorderLayout.SOUTH
                    )

                    frame.setSize(850, 650)

                    frame.setLocationRelativeTo(null)

                    frame.setDefaultCloseOperation(
                        WindowConstants.DISPOSE_ON_CLOSE
                    )

                    frame.setVisible(true)
                }
            }
        )

        println("IMAGE CONVERTED SUCCESSFULLY!")
        println("Resolution: " + w + " x " + h)
        println("Total Strokes: " + strokes)

    }

} catch {

    case e: Exception =>

        println("TURTLE GENERATOR ERROR:")
        println(e.toString)

        JOptionPane.showMessageDialog(
            null,
            "ERROR:\n" + e.toString
        )
}