about summary refs log tree commit diff stats
path: root/js/story-interpreter/world.dsl
blob: 3e75a7a4ec95d69512bd24374af5fdf76e43fce1 (plain) (blame)
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
room "Kitchen" {
    description "A small, cozy kitchen. There's a smell of cookies baking."
    
    item "Cookie Jar" {
        description "A ceramic jar filled with delicious cookies."
        action "take" {
            effect "You take a cookie from the jar."
        }
    }

    animal "Cat" {
        description "A small black cat is sitting on the counter."
        action "talk" {
            effect "The cat meows at you."
        }
    }

    connection "north" to "Living Room"
}

room "Living Room" {
    description "A large living room with a comfortable couch and a TV."
    
    item "Remote Control" {
        description "A remote control for the TV."
        action "use" {
            effect "You turn on the TV. The news is on."
        }
    }

    connection "south" to "Kitchen"
}
.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; } td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } .highlight .hll { background-color: #ffffcc } .highlight .c { color: #888888 } /* Comment */ .highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ .highlight .k { color: #008800; font-weight: bold } /* Keyword */ .highlight .ch { color: #888888 } /* Comment.Hashbang */ .highlight .cm { color: #888888 } /* Comment.Multiline */ .highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */ .highlight .cpf { color: #888888 } /* Comment.PreprocFile */ .highlight .c1 { color: #888888 } /* Comment.Single */ .highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */ .highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */ .highlight .gr { color: #aa0000 } /* Generic.Error */ .highlight .gh { color: #333333 } /* Generic.Heading */ .highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ .highlight .go { color: #888888 } /* Generic.Output */ .highlight .gp { color: #555555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666666 } /* Generic.Subheading */ .highlight .gt { color: #aa0000 } /* Generic.Traceback */ .highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
const toggleCameraButton = document.getElementById('toggleCamera');
const captureFrameButton = document.getElementById('captureFrame');
const captureVideoButton = document.getElementById('captureVideo');
const video = document.getElementById('webcam');
const canvas = document.getElementById('ditheredOutput');
const context = canvas.getContext('2d');

let stream = null;
let isCameraOn = false;
const lowResWidth = 160; // Gameboy camera resolution: 160×144
const lowResHeight = 144;
const videoLength = 3000; // 3 seconds
video.style.width = lowResWidth + 'px';
video.style.height = lowResHeight + 'px';

// This is a utility function I'm using to try and debut why Safari is claiming that "NotSupportedError: mimeType is not supported"
const getSupportedMimeType = possibleTypes => {
    for (let i = 0; i < possibleTypes.length; i++) {
        if (MediaRecorder.isTypeSupported(possibleTypes[i])) {
            return possibleTypes[i];
        }
    }
    return false;
}
// console.log(getSupportedMimeType(['video/webm;codecs=vp8', 'video/webm', 'video/mp4']));

toggleCameraButton.addEventListener('click', async () => {
    if (!isCameraOn) {
        try {
            let constraints = { video: true };
            if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
                constraints = { 
                    video: {
                        width: { ideal: 1280 },
                        height: { ideal: 720 },
                        facingMode: 'environment' 
                    } 
                };
            }
            stream = await navigator.mediaDevices.getUserMedia(constraints);
            video.srcObject = stream;
            video.style.display = 'block';
            isCameraOn = true;
            toggleCameraButton.textContent = 'Turn Camera Off';
            captureFrameButton.disabled = false;
            captureVideoButton.disabled = false;
            captureFrameButton.classList.add('active');
            captureVideoButton.classList.add('active');
            video.addEventListener('loadeddata', () => {
                canvas.width = lowResWidth;
                canvas.height = lowResHeight;
                requestAnimationFrame(processFrame);
            });
        } catch (err) {
            console.error('Failed to access the camera: ', err);
        }
    } else {
        stream.getTracks().forEach(track => track.stop());
        video.style.display = 'none';
        isCameraOn = false;
        toggleCameraButton.textContent = 'Turn Camera On';
        captureFrameButton.disabled = true;
        captureVideoButton.disabled = true;
        captureFrameButton.classList.remove('active');
        captureVideoButton.classList.remove('active');
    }
});

captureFrameButton.addEventListener('click', () => {
    const link = document.createElement('a');
    link.href = canvas.toDataURL('image/png');
    link.download = 'dithered-frame.png';
    link.click();
});

captureVideoButton.addEventListener('click', () => {
    const startRecording = (canvas, duration, frameRate) => {
        return new Promise((resolve, reject) => {
            const stream = canvas.captureStream(frameRate);
            if (!stream) {
                const errtxt = 'Stream capture from canvas failed.';
                console.error(errtxt);
                return reject(errtxt);
            }

            const mimeType = getSupportedMimeType(['video/webm;codecs=vp8', 'video/webm', 'video/mp4']);
            const mediaRecorder = new MediaRecorder(stream, { mimeType: mimeType });
            let chunks = [];

            mediaRecorder.ondataavailable = (event) => {
                if (event.data.size > 0) {
                    chunks.push(event.data);
                }
            };

            mediaRecorder.onstop = () => {
                const blob = new Blob(chunks, { type: mimeType });
                resolve(blob);
            };

            mediaRecorder.onerror = (event) => {
                console.error('MediaRecorder error:', event.error);
                reject(event.error);
            };

            // Set the frame rate
            mediaRecorder.onstart = () => {
                const options = mediaRecorder.videoBitsPerSecond;
                mediaRecorder.videoBitsPerSecond = options * frameRate;
            };

            mediaRecorder.start();
            captureVideoButton.disabled = true;
            captureVideoButton.textContent = 'Recording...';
            setTimeout(() => {
                mediaRecorder.stop();
                captureVideoButton.disabled = false;
                captureVideoButton.textContent = 'Capture Video';
            }, duration);
        });
    };

    const handleCaptureVideo = async () => {
        if (!isCameraOn) {
            console.error('Camera is not active.');
            return;
        }

        try {
            captureVideoButton.disabled = true;
            const frameRate = 10; // Frame rate
            const videoBlob = await startRecording(ditheredOutput, videoLength, frameRate);
            const videoURL = URL.createObjectURL(videoBlob);

            const videoLink = document.createElement('a');
            videoLink.href = videoURL;
            if (videoBlob.type === 'video/mp4') {
                videoLink.download = 'dithered-video.mp4';
            } else {
                videoLink.download = 'dithered-video.webm';
            }
            videoLink.click();

            // Enable the button again after recording
            captureVideoButton.disabled = false;
        } catch (error) {
            console.error('Error recording video:', error);
            captureVideoButton.disabled = false;
        }
    };

    handleCaptureVideo();
});


function processFrame() {
    if (!isCameraOn) {
        console.error('Camera is not active.');
        return;
    }

    // Crop and draw the middle part of the video frame
    const videoAspect = video.videoWidth / video.videoHeight;
    const canvasAspect = lowResWidth / lowResHeight;
    let sx, sy, sw, sh;
    if (videoAspect > canvasAspect) {
        sw = video.videoHeight * canvasAspect;
        sh = video.videoHeight;
        sx = (video.videoWidth - sw) / 2;
        sy = 0;
    } else {
        sw = video.videoWidth;
        sh = video.videoWidth / canvasAspect;
        sx = 0;
        sy = (video.videoHeight - sh) / 2;
    }
    context.drawImage(video, sx, sy, sw, sh, 0, 0, lowResWidth, lowResHeight);
    const frame = context.getImageData(0, 0, lowResWidth, lowResHeight);
    applyFloydSteinbergDithering(frame);
    context.putImageData(frame, 0, 0);
    requestAnimationFrame(processFrame);
}

function applyFloydSteinbergDithering(imageData) {
    const { data, width, height } = imageData;

    // Helper to access and set pixel values
    const getPixelIndex = (x, y) => (y * width + x) * 4;
    const getPixelValue = (x, y) => data[getPixelIndex(x, y)];
    const setPixelValue = (x, y, value) => {
        const index = getPixelIndex(x, y);
        data[index] = value;
        data[index + 1] = value;
        data[index + 2] = value;
    };

    // Helper that clamps a value between 0 and 255
    const clamp = (value) => Math.max(0, Math.min(255, value));

    // Process a single pixel
    const processPixel = (x, y) => {
        const oldPixel = getPixelValue(x, y);
        const newPixel = oldPixel < 128 ? 0 : 255; // Make it 1-bit black and white
        setPixelValue(x, y, newPixel);
        const quantError = oldPixel - newPixel;

        // Spread the error to neighboring pixels
        if (x + 1 < width) {
            const idx = getPixelIndex(x + 1, y);
            data[idx] = clamp(data[idx] + quantError * 7 / 16);
        }
        if (x - 1 >= 0 && y + 1 < height) {
            const idx = getPixelIndex(x - 1, y + 1);
            data[idx] = clamp(data[idx] + quantError * 3 / 16);
        }
        if (y + 1 < height) {
            const idx = getPixelIndex(x, y + 1);
            data[idx] = clamp(data[idx] + quantError * 5 / 16);
        }
        if (x + 1 < width && y + 1 < height) {
            const idx = getPixelIndex(x + 1, y + 1);
            data[idx] = clamp(data[idx] + quantError * 1 / 16);
        }
    };

    // Process each pixel in the image one by one
    // FIXME: There has to be a better way to do this, right?
    for (let y = 0; y < height; y++) {
        for (let x = 0; x < width; x++) {
            processPixel(x, y);
        }
    }
}

function clamp(value) {
    return Math.max(0, Math.min(255, value));
}