Repository: mcmonkeyprojects/sd-infinity-grid-generator-script Branch: master Commit: 0082d79eb9a4 Files: 16 Total size: 190.6 KB Directory structure: gitextract_jp1goxq0/ ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── LICENSE.txt ├── README.md ├── assets/ │ ├── a1111webui.js │ ├── grid.schema.json │ ├── images/ │ │ └── put-usable-images-here.txt │ ├── jsgif.js │ ├── page.html │ ├── proc.js │ └── styles.css ├── gridgencore.py ├── install.py ├── javascript/ │ └── infinity_grid.js ├── scripts/ │ └── infinity_grid.py └── style.css ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ github: mcmonkey4eva ================================================ FILE: .gitignore ================================================ .vscode/ assets/*.yml assets/styles-user.css __pycache__/ assets/images/**/*.png assets/images/**/*.jpg assets/images/**/*.webp ================================================ FILE: LICENSE.txt ================================================ The MIT License (MIT) Copyright (c) 2022-2023 Alex "mcmonkey" Goodwin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # Stable Diffusion Infinity Grid Generator ![img](github/megagrid_ref.png) ### Concept Extension for the [AUTOMATIC1111 Stable Diffusion WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) that generates infinite-dimensional grids. An "infinite axis grid" is like an X/Y plot grid, but with, well, more axes on it. Of course, monitors are 2D, so this is implemented in practice by generating a webpage that lets you select which two primary axes to display, and then choose the current value for each of the other axes. ### Goals and Use Cases The primary goal is to let people generate their own fancy grids to explore how different settings affect their renders in a convenient form. Another goal of this system is to develop educational charts, to provide a universal answer to the classic question of "what does (X) setting do? But what about with (Y)?" - [The MegaGrid](https://sd.mcmonkey.org/megagrid/). There is a built in ability to add description text to fields, for the specific purpose of enhancing educational page output. ### Pros/Cons The advantage of this design is it allows you to rapidly compare the results of different combinations of settings, without having to wait to for generation times for each specific sub-grid as-you-go - you just run it all once in advance (perhaps overnight for a large run), and then after that browse through it in realtime. The disadvantage is that time to generate a grid is exponential - if you have 5 samplers, 5 seeds, 5 step counts, 5 CFG scales... that's 5^4, or 625 images. Add another variable with 5 options and now it's 3125 images. You can see how this quickly jumps from a two minute render to a two hour render. -------------- ### Table of Contents - [Examples](#Examples) - [Status](#Status) - [Installation](#Installation) - [Basic Usage](#Basic-Usage) - [Advanced Usage](#Advanced-Usage) - [1: Grid Definition File](#1-grid-definition-file) - [Supported Extensions](#supported-extensions) - [Dynamic Thresholding (CFG Scale Fix)](#dynamic-thresholding-cfg-scale-fix) - [ControlNet](#controlnet) - [2: Grid Content Generation via WebUI](#2-grid-content-generation-via-webui) - [3: Using The Output](#3-using-the-output) - [4: Expanding Later](#4-expanding-later) - [Credits](#credits) - [Common Issues](#common-issues) - [License](#License) -------------- ### Examples Here's a big MegaGrid using almost every mode option in one, with detailed educational descriptions on every part: https://sd.mcmonkey.org/megagrid/ Here's a very small web demo you can try to test how the output looks and works: https://mcmonkeyprojects.github.io/short_example and you can view the generated asset files for that demo [here](https://github.com/mcmonkeyprojects/mcmonkeyprojects.github.io/tree/master/short_example). ![img](github/simple_ref.png) -------------- ### Status Current overall project status (as of December 2023): **Works well, actively maintained**. Has been generally well tested. The core has been ported to other environments and stress-tested for multiple real projects that depend on large grids and rapid grid analysis. A version of this project is also available for [StableSwarmUI, here](https://github.com/Stability-AI/StableSwarmUI/blob/master/src/BuiltinExtensions/GridGenerator/README.md) which also lets you use it with Comfy and other backends -------------- ### Installation - You must have the [AUTOMATIC1111 Stable Diffusion WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) already installed and working. Refer to that project's readme for help with that. - Open the WebUI, go to to the `Extensions` tab - -EITHER- Option **A**: - go to the `Available` tab with - click `Load from` (with the default list) - Scroll down to find `Infinity Grid Generator`, or use `CTRL+F` to find it - -OR- Option **B**: - Click on `Install from URL` - Copy/paste this project's URL into the `URL for extension's git repository` textbox: `https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script` - Click `Install` - Restart or reload the WebUI -------------- ### Basic Usage ![img](github/create_in_ui_demo.png) - Basic usage is very simple! - select the script under `Scripts` - Leave file as `Create in UI` - Select `Axis 1 Mode` as whatever mode you want, like `Seed` or `Sampler` - In the `Axis 1 Value` box, you can type a comma-separated list like `1, 2, 3`, or a double-pipe separated list like `1girl, booru style, prompt || 1boy, has commas, so pipes avoid problems` - Repeat for as many axes as you want. When you configure axis #4, it will automatically add 4 more rows of axes to fill in. Leave any extras empty. - Click your main `Generate` button and wait for it to finish. - When it's done, click the button labeled `Page will be at (Click me) outputs/...` to view the full page. - Note that a `config.yml` is saved in the output directory, which you can copy to your `assets` folder if you want to reuse it. -------------- ### Advanced Usage Usage comes in three main steps: - [1: Build a grid definition](#1-grid-definition-file) - [2: Generate its contents](#2-grid-content-generation-via-webui) - [3: View/use the generated output page](#3-using-the-output) - You can also [expand your grid later](#4-expanding-later) -------------- ### 1: Grid Definition File ![img](github/yaml_settings_blur.png) - Grid information is defined by **YAML files**, in the extension folder under `assets`. Find the `assets/short_example.yml` file to see an example of the full format. **If you do not want to follow an example file:** - You can **create new files** in the assets directory (as long as the `.yml` extension stays), or copy/paste an example file and edit it. I recommend you do not edit the actual example file directly to avoid git issues. - I recommend editing with a **good text editor**, such as *VS Code* or *Notepad++*. Don't use *MS Word* or *Windows Notepad* as those might cause trouble. - All text inputs allow for **raw HTML**, so, be careful. You can use `<` for `<`, and `>` for `>`, `:` for `:`, and `&` for `&`. - The file must have key `grid`, with subkey `title` and `description` to define the file data. - It must also have `format` as `jpg` or `png` - It can optionally also have `params` to specify any default parameters. - It can optionally define `show descriptions`, `autoscale`, and `sticky` as `true` or `false` to change default web-viewer settings. - It can optionally define `x axis`, `y axis`, `x super axis`, and `y super axis` as axis IDs to change the default web-viewer axes. - The file can optionally have key `variables` with subkey/value pairs as replacements, for example `(type): waffle` - then later in a param value you can use `a picture of a (type)` to automatically fill the variable. These can be in any format you desire, as they are simple text replacements. They apply to all values, including titles, descriptions, and params (this was added for [valconius in issue #16](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script/issues/16)). - The file must have key `axes` to define the list of axes. This is a map-list key - meaning, add subkeys to create a list of each axis. - The simplest format for an axis is a setting name as the key and a comma-separated list of values inside. - For example, `seed: 1, 2, 3` is a valid and complete axis. - If commas may be problematic, you many instead use two pipes `||` to separate values - for example `prompt: 1girl, booru style, commas || 1boy, more commas, etc`. If `||` is used, commas will be ignored for splitting - For numeric inputs, you can use ellipses notation to quickly shorthand long lists. For example: `seed: 1, 2, ..., 10` automatically fills to `1, 2, 3, 4, 5, 6, 7, 8, 9, 10`. Or, `cfg scale: 7.0, 7.1, ..., 7.8` automatically fills to `7.0, 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.8`. - Note that you must have two entries before and one after - the step rate is defined as the space between the two prior and the total range is defined as between the one prior and the one after. - You can use ellipses multiple times in one set, for example `1, 2, ..., 6, 8, ... 14` will fill to `1, 2, 3, 4, 5, 6, 8, 10, 12, 14` (note how 1-6 are spaced 1 apart, but 6-14 are spaced two apart). - Each axis must have a `title`, and `values`. It can optionally have a `description`. - You can also optionally have `default: (value_id)` to set the default selected tab. - There are two ways to do a value in the value list: - Option 1: just do like `steps=10` ... this will set title to `10`, and param `steps` to value `10`, with no description. - Option 2: Add a submapping with key `title`, and optional `description`, and then `params` as a sub map of parameters like `steps: 10` - A value with a full format can be set to skip rendering via adding `skip: true`. This is useful for eg if some values are only valid in certain combinations, you can do runs with some skipped. Skipped values will be kept in the HTML output. - A value may specify `show: false` to default uncheck the 'Show value' advanced option. Micro example: ```yml grid: title: Tiny example author: someone description: This is just to show core format. View the example `.yml` files in assets for better examples. format: jpg axes: sampler: Euler, DDIM seed: 1, 2, 3 ``` - Names and descriptions can always be whatever you want, as HTML text. #### Settings supported for parameters | Name | Type | Example | Notes | | --- | --- | --- | ----------- | | `Sampler` | Named | `DDIM`, `euler`, ... | | | `Model` | Filename | `sd-v1-5` | Note that `Model` and `VAE` are **global settings**, and as such you should not have an axis where some values specify one of those params but others don't, as this will cause an unpredictable model selection for the values that lack specificity. | | `VAE` | Filename | `kl-f8-anime2` | See note on `Model` above | | `Prompt` | Text | `a cat` | | | `Negative Prompt` | Text | `gross, weird, bad` | | | `Prompt Replace` | Text-Pair | `some_tag = new text here` | Note the `=` symbol to separate the original text with the new text. That will change a prompt of for example `my prompt with some_tag stuff` to `my prompt with new text here stuff`.
Unlike other modes, the PromptReplace is case-sensitive - if you use capitals in your prompt, you need capitals in your replace matcher.
If you want multiple replacements in one value, you can number them, like `Prompt Replace 1` and `Prompt Replace 2` and etc.
When building a simple list in UI, you can just do eg `cat, dog, waffle` and it will understand to replace `cat` in the base prompt first with `cat`, then `dog`, then `waffle` (ie you can skip the `=` for simple usages). | | `Styles` | Text | `photo`, `cartoon`, ... | Automatically includes UI styles to your prompt. Can use comma-separated list to have multiple. Note this means in the UI you can do for example `photo, cinematic ||| anime, cartoon` to compare multiple combos easily. | | `Seed` | Integer | `1`, `2`, `3`, ... | | | `Steps` | Integer | `20`, `50`, ... | | | `CFG Scale` | Decimal | `5`, `7.5`, `12`, ... | | | `Width` | Integer | `512`, `768`, ... | Initial generation width. | | `Height` | Integer | `512`, `768`, ... | Initial generation height. | | `Out Width` | Integer | `512`, `768`, ... | What resolution to save the image as (if unspecified, uses `Width`). Useful to save filespace. | | `Out Height` | Integer | `512`, `768`, ... | Refer to `Out Width`. | | `Clip Skip` | Integer | `1`, `2` | Use `2` for NAI-like models, `1` for the rest. | | `Var Seed` | Integer | `0`, `1`, ... | Variation seed, use with `Var Strength`. | | `Var Strength` | Decimal | `0`, `0.5`, ..., `1` | Variation seed strength. | | `Restore Faces` | Named | `true`, `false`, `GFPGan`, `CodeFormer` | Limited to the given example inputs only. | | `CodeFormer Weight` | Decimal | `0`, `0.5`, ..., `1` | Only applicable if `Restore Faces` is set to `CodeFormer`. | | `Denoising` | Decimal | `0`, `0.5`, ..., `1` | Denoising strength for img2img or HR fix. | | `ETA` | Decimal | `0`, `0.5`, ..., `1` | ? | | `ETA Noise Seed Delta` | Integer | `0`, `31337` | use `31337` to replicate NovelAI results, use `0` for anything else. Not very useful. | | `Sigma Churn` | Decimal | `0`, `0.5`, ..., `1` | Sampler parameter, rarely used. | | `Sigma Tmin` | Decimal | `0`, `0.5`, ..., `1` | Sampler parameter, rarely used. | | `Sigma Tmax` | Decimal | `0`, `0.5`, ..., `1` | Sampler parameter, rarely used. | | `Sigma Noise` | Decimal | `0`, `0.5`, ..., `1` | Sampler parameter, rarely used. | | `Tiling` | Boolean | `true`, `false` | Useful for textures. | | `Image Mask Weight` | Decimal | `0`, `0.5`, ..., `1` | Conditional image mask weight. Only applies to img2img or HR fix. | | `Enable Highres Fix` | Boolean | `true`, `false` | Required for other HR settings to work. Defaults denoising strength to `0.75` if not specified. Only valid in txt2img. | | `Highres Scale` | Decimal | `2`, `2.5`, ..., `16` | How much to scale by for HR fix. | | `Highres Steps` | Integer | `20`, `50`, ... | Secondary steps for HR fix. | | `Highres Upscaler` | Named | `None`, `Latent`, ... | Upscaler mode to use prior to running Highres Fix. | | `Highres Resize Width` | Integer | `512`, `768`, ... | Resolution to target as final output size for Highres Fix, overrides `Highres Scale`. | | `Highres Resize Height` | Integer | `512`, `768`, ... | See `Highres Resize Width` above. | | `Highres Upscale To Width` | Integer | `512`, `768`, ... | Resolution to upscale to prior to running Highres Fix. | | `Highres Upscale To Height` | Integer | `512`, `768`, ... | See `Highres Upscale To Height` above. | | `Image CFG Scale` | Decimal | `5`, `7.5`, `12`, ... | Image CFG Scale, for Instruct pix2pix usage. | | `Use Result Index` | Integer | `0`, `1`, ... | Special trick to get a non-zero result image index, eg for ControlNet secondary output image. | - All setting names are **case insensitive and spacing insensitive**. That means `CFG scale`, `cfgscale`, `CFGSCALE`, etc. are all read as the same. - Inputs where possible also similarly insensitive, including model names. - Inputs have error checking at the start, to avoid the risk of it working fine until 3 hours into a very big grid run. - Note that it will be processed from bottom to top - so if you have first `samplers` DDIM and Euler, then `steps` 20 and 10, then `seeds` 1 and 2, it will go in this order: - Sampler=DDIM, Steps=20, Seed=1 - Sampler=DDIM, Steps=20, Seed=**2** - Sampler=DDIM, Steps=**10**, Seed=1 - Sampler=DDIM, Steps=10, Seed=2 - Sampler=**Euler**, Steps=20, Seed=1 - Sampler=Euler, Steps=20, Seed=2 - Sampler=Euler, Steps=10, Seed=1 - Sampler=Euler, Steps=10, Seed=2 - So, things that take time to load, like `Model`, should be put near the top, so they don't have to be loaded repeatedly. -------------- ### Supported Extensions #### Dynamic Thresholding (CFG Scale Fix) Extension docs: | Name | Type | Example | Notes | | --- | --- | --- | ----------- | | `DynamicThreshold Enable` | Boolean | `true`, `false` | | | `DynamicThreshold Mimic Scale` | Decimal | `5`, `7.5`, `12`, ... | | | `DynamicThreshold Threshold Percentile` | Decimal | `0`, `0.5`, ..., `1.0` | | | `DynamicThreshold Mimic Mode` | Named | `Constant`, `Linear Down`, `Cosine Down`, `Half Cosine Down`, `Linear Up`, `Cosine Up`, `Half Cosine Up`, `Power Up` | | | `DynamicThreshold CFG Mode` | Named | `Constant`, `Linear Down`, `Cosine Down`, `Half Cosine Down`, `Linear Up`, `Cosine Up`, `Half Cosine Up`, `Power Up` | | | `DynamicThreshold Mimic Scale Minimum` | Decimal | `5`, `7.5`, `12`, ... | | | `DynamicThreshold CFG Scale Minimum` | Decimal | `5`, `7.5`, `12`, ... | | | `DynamicThreshold Power Value` | Decimal | `2`, `4`, ... | For `Power Up` mode only. | | `DynamicThreshold Scaling Startpoint` | Named | `ZERO`, `MEAN` | | | `DynamicThreshold Variability Measure` | Named | `STD`, `AD` | | | `DynamicThreshold Interpolate Phi` | Decimal | `0`, `0.5`, ..., `1.0` | | | `DynamicThreshold Separate Feature Channels` | Boolean | `true`, `false` | | #### ControlNet Extension docs: Note: must enable `Allow other script to control this extension` in `Settings` -> `ControlNet` | Name | Type | Example | Notes | | --- | --- | --- | ----------- | | `ControlNet Enable` | Boolean | `true`, `false` | | | `ControlNet Preprocessor` | Named | `none`, `canny`, `depth`, `hed`, `mlsd`, `normal_map`, `openpose`, `openpose_hand`, `pidinet`, `scribble`, `fake_scribble`, `segmentation` | | | `ControlNet Model` | Named | `diff_control_sd15_canny_fp16`, ... | | | `ControlNet Weight` | Decimal | `0.0`, `0.5`, ..., `2.0` | | | `ControlNet Guidance Strength` | Decimal | `0.0`, `0.5`, ..., `1.0` | | | `ControlNet Annotator Resolution` | Integer | `64`, `512`, ..., `2048` | | | `ControlNet Threshold A` | Integer | `64`, `512`, ..., `256` | | | `ControlNet Threshold B` | Integer | `64`, `512`, ..., `256` | | | `ControlNet Image` | Text | `pose.png`, `otherpose.jpg`, ... | Put image files in `(EXTENSION FOLDER)/assets/images/`, as `png`, `jpg`, or `webp`. Subfolders allowed. | #### Other Extensions - Any extension has the ability to add its own modes with the following code: ```py # Verify grid extension is present import importlib if importlib.util.find_spec("gridgencore") is not None: import gridgencore from gridgencore import GridSettingMode # p is the SD processing object, v is the value def apply(p, v): p.some_setting_here = v # dry: bool, type: str, apply: callable, min: float = None, max: float = None, clean: callable = None gridgencore.registerMode("mySettingNameHere", GridSettingMode(True, "text", apply)) # for apply if the param is a 'p' field, you can use gridgencore.apply_field("fieldname") ``` -------------- ### 2: Grid Content Generation via WebUI ![img](github/webui_ref.png) - Open the WebUI - Go to the `txt2img` or `img2img` tab - At the bottom of the page, find the `Script` selection box, and select `Generate Infinite-Axis Grid` - Select options at will. You can hover your mouse over each option for extra usage information. - Select your grid definition file from earlier. - If it's not there, you might just need to hit the Refresh button on the right side. - If it's still not, there double check that your file is in the `assets/` folder of the extension, and that it has a proper `.yml` extension. - Hit your `Generate` button (the usual big orange one at the top), and wait. - The output folder will be named based on your `.yml` file's name. -------------- ### 3: Using The Output ![img](github/files_ref.png) - Find the `index.html` file - It's normally in `(your grid output directory)/(filename)/index.html` - The example file might output to `outputs/grids/short_example/index.html` - Open the HTML file in a browser. Enjoy. - If you want to share the content, just copy/paste the whole folder into a webserver somewhere. - Or upload to github and make GitHub.io pages host it for you. [See example here](https://github.com/mcmonkeyprojects/mcmonkeyprojects.github.io) - You have a few different clickable options: - `Show descriptions of axes and values`: if you used descriptions, you can uncheck this box to hide them. Helps save space for direct viewing. - `Auto-scale images to viewport width`: this is handy for a few different scenarios - A: if your images are small and your screen is big, checking this option makes them bigger - B: if your images are so big they're going off the edge, checking this option makes them smaller - C: if checked, you can zoom in/out of the page using your browser zoom (CTRL + Mouse Wheel) to change the UI size without affecting the image size - if unchecked, you can zoom in/out to change the size of the images. - `Sticky navigation`: when checked, the navigation will stick to the top of the screen as you scroll down. Helps you quickly change axes while scrolling around without losing your place. - `Advanced Settings`: when clicked, it will open a dropdown with more advanced settings - ![img](github/advanced_settings_ref.png) - `Auto cycle every (x) seconds`: you can set these to non-zero values to the grid automatically change settings over time. For example, if you set your "Seed" option to "3 seconds", then every 3 seconds the seed will change (cycling between the options you have in order). This was suggested by [itswhateverman in issue #2](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script/issues/2). - `Show value`: you can uncheck any box to hide a value from the grid. Helps if you want to ignore some of the values and get a clean grid of just the ones you care about. This was suggested by [piyarsquare in issue #4](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script/issues/4). - You can also click on any image to view it fullscreen and see its metadata (if included in output). While in this mode, you can use arrow keys to quick navigate between images, or press Escape to close (This suggested by [itswhateverman in issue #5](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script/issues/5) and [issue #17](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script/issues/17)). - You can also set the `X Super-axis` and `Y Super-axis` to unique axes to get a grid-of-grids! - ![img](github/super_axis_demo.png) - You can also quicksave preview images of the grid, or even generate GIFs that autoscroll through an axis, all with a few easy buttons on the viewer page! -------------- ### 4: Expanding Later If you want to add more content to a grid you already made, you can do that: - Use the same `yml` file. - You can add new values to an axis freely. - If you remove values, they will be excluded from the output but pre-existing generated images won't be removed. - You can add axes, but you'll have to regenerate all images if so. - Probably save as a new filename in that case. - If you're just adding a new value, make sure to leave `overwriting existing images` off. ---------------------- ### Credits - This design was partially inspired by the "XYZ Plot" script by "xrypgame" (not to be confused with the "XYZ Plot" script in Auto WebUI which is actually just the "X/Y Plot" script but they added a "Z" lol) - Sections of code are referenced from the WebUI itself, and its default "X/Y Plot" script (since renamed to labeled "XYZ Plot"). - Some sections of code were referenced from various other relevant sources, for example the Dreambooth extension by d8ahazard was referenced for a JavaScript code trick (titles override). - Some sections of code were referenced from, well, random StackOverflow answers and a variety of other googled up documentation and answer sites. I haven't kept track of them, but I'm glad to live in a world where so many developers are happy and eager to help each other learn and grow. So, thank you to all members of the FOSS community! - Thanks to the authors of all [merged PRs](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script/pulls?q=is%3Apr+is%3Aclosed+is%3Amerged). - Thanks to the authors of all issues labeled as [Completed](https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script/issues?q=label%3ACompleted). - Thanks to StabilityAI, RunwayML, CompVis for Stable Diffusion, and the researchers whose work was incorporated. - Thanks to AUTOMATIC1111 and the long list of contributors for the WebUI. ---------------------- ### Common Issues ``` File "stable-diffusion-webui\modules\images.py", line 508, in _atomically_save_image image_format = Image.registered_extensions()[extension] KeyError: '.jpg' ``` If you have this error, just hit generate again. I'm not sure why it happens, it just does at random sometimes on the first time the WebUI starts up. It seems to happen when you use `OutWidth`/`OutHeight` settings and is prevented by running any generation without a custom out-resolution. Might be some required initialization is getting skipped when an image is rescaled? ---------------------- ### Licensing pre-note: This is an open source project, provided entirely freely, for everyone to use and contribute to. If you make any changes that could benefit the community as a whole, please contribute upstream. ### The short of the license is: You can do basically whatever you want, except you may not hold any developer liable for what you do with the software. ### The long version of the license follows: The MIT License (MIT) Copyright (c) 2022-2023 Alex "mcmonkey" Goodwin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: assets/a1111webui.js ================================================ /** * This file is part of Infinity Grid Generator, view the README.md at https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script for more information. */ function genParamQuote(text) { // Referenced to match generation_parameters_copypaste.py - quote(text) if (!text.includes(',')) { return text; } return '"' + text.toString().replaceAll('\\', '\\\\').replaceAll('"', '\\"') + '"'; } function formatMet(name, val, bad) { if (val == null) { return ''; } val = val.toString(); if (bad != undefined && val == bad) { return ''; } return name + ': ' + genParamQuote(val) + ', '; } function formatMetadata(valSet) { var count = Object.keys(valSet).length; if (count == 0) { return ''; } else if (count == 1) { return valSet['error']; } // Referenced to match processing.py - create_infotext(p) var negative = valSet['negativeprompt']; if (negative.length > 0) { negative = '\nNegative prompt: ' + negative; } const handled = ['steps', 'sampler', 'cfgscale', 'seed', 'restorefaces', 'width', 'height', 'model', 'varseed', 'varstrength', 'denoising', 'eta', 'clipskip', 'vae', 'sigmachurn', 'sigmatmin', 'sigmatmax', 'sigmanoise', 'prompt', 'negativeprompt', 'codeformerweight']; var keyData = formatMet('Steps', valSet['steps']) + formatMet('Sampler', valSet['sampler']) + formatMet('CFG scale', valSet['cfgscale']) + formatMet('Seed', valSet['seed']) + formatMet('Face restoration', valSet['restorefaces'], 'false') + formatMet('Size', valSet['width'] + 'x' + valSet['height']) // model hash + formatMet('Model', valSet['model']) // Batch size, batch pos + formatMet('Variation seed', valSet['varseed'], '0') + formatMet('Variation seed strength', valSet['varstrength'], '0') // Seed resize from + formatMet('Denoising strength', valSet['denoising']) // Conditional mask weight + formatMet('Eta', valSet['eta']) + formatMet('Clip skip', valSet['clipskip'], '1') // ENSD ; // Not part of normal gen-params var extraData = formatMet('VAE', valSet['vae']) + formatMet('Sigma Churn', valSet['sigmachurn'], '0') + formatMet('Sigma T-Min', valSet['sigmatmin'], '0') + formatMet('Sigma T-Max', valSet['sigmatmax'], '1') + formatMet('Sigma Noise', valSet['sigmanoise'], '1') + (valSet['restorefaces'] == 'CodeFormer' ? formatMet('CodeFormer Weight', valSet['codeformerweight']) : ''); var lastData = ''; for (const [key, value] of Object.entries(valSet)) { if (!handled.includes(key) && value != null) { lastData += `${key}: ${value}, `; } } if (lastData.length > 2) { lastData = '\n(Other): ' + lastData.substring(0, lastData.length - 2); } keyData = keyData.substring(0, keyData.length - 2); if (extraData.length > 2) { extraData = extraData.substring(0, extraData.length - 2); } return valSet['prompt'] + negative + '\n' + keyData + '\n' + extraData + lastData; } function crunchParamHook(data, key, value) { if (key == 'promptreplace') { var replacers = value.split('=', 2); var match = replacers[0].trim(); var replace = replacers[1].trim(); data['prompt'] = data['prompt'].replaceAll(match, replace); data['negativeprompt'] = data['negativeprompt'].replaceAll(match, replace); return true; } return false; } ================================================ FILE: assets/grid.schema.json ================================================ { "$schema": "http://json-schema.org/draft-06/schema#", "type": "object", "properties": { "grid": { "$ref": "#/definitions/Grid" }, "axes": { "$ref": "#/definitions/Axes" }, "variables": { "$ref": "#/definitions/Variables" } }, "required": [ "axes", "grid" ], "title": "InfinityGrid", "definitions": { "Variables": { "type": "object", "patternProperties": { "\\(.*\\)": { "oneOf": [ {"type": "string"}, {"type": "number"} ] } } }, "Axes": { "type": "object", "patternProperties": { ".*": { "$ref": "#/definitions/Axis" } }, "title": "Axes" }, "Axis": { "oneOf": [{ "type": "string" }, { "type": "object", "properties": { "title": { "oneOf": [ {"type": "string"}, {"type": "number"} ] }, "default": { "oneOf": [{ "type": "string" }, { "type": "number" } ] }, "description": { "type": "string" }, "values": { "patternProperties": { ".*": { "$ref": "#/definitions/Value" } } } }, "required": ["title", "values"] }] }, "Value": { "oneOf": [{ "type": "string", "pattern": "(Sampler|sampler|Model|model|VAE|vae|Prompt|prompt|NegativePrompt|negativeprompt|Negative Prompt|negative prompt|PromptReplace|promptreplace|Prompt Replace|prompt replace|Prompt Replace|prompt replace|Seed|seed|Steps|steps|CFGScale|cfgscale|CFG Scale|cfg scale|CFGscale|CFG scale|Width|width|Height|height|OutWidth|outwidth|Out Width|out width|OutHeight|outheight|Out Height|out height|ClipSkip|clipskip|Clip Skip|clip skip|VarSeed|varseed|Var Seed|var seed|VarStrength|varstrength|Var Strength|var strength|CodeFormerWeight|codeformerweight|CodeFormer Weight|codeformer weight|Denoising|denoising|ETA|eta|ETANoiseSeedDelta|etanoiseseeddelta|ETA Noise Seed Delta|eta noise seed delta|SigmaChurn|sigmachurn|Sigma Churn|sigma churn|SigmaTmin|sigmatmin|Sigma Tmin|sigma tmin|SigmaTmax|sigmatmax|Sigma Tmax|sigma tmax|SigmaNoise|sigmanoise|Sigma Noise|sigma noise|Tiling|tiling|ImageMaskWeight|imagemaskweight|Image Mask Weight|image mask weight|EnableHighresFix|enablehighresfix|Enable Highres Fix|enable highres fix|HighresScale|highresscale|Highres Scale|highres scale|HighresSteps|highressteps|Highres Steps|highres steps|HighresUpscaler|highresupscaler|Highres Upscaler|highres upscaler|HighresResizeWidth|highresresizewidth|Highres Resize Width|highres resize width|HighresResizeHeight|highresresizeheight|Highres Resize Height|highres resize height|HighresUpscaleToWidth|highresupscaletowidth|Highres Upscale To Width|highres upscale to width|HighresUpscaleToHeight|highresupscaletoheight|Highres Upscale To Height|highres upscale to height|RestoreFaces|Restore Faces|restorefaces|restore faces|([dD]ynamic\\s?[Tt]hreshold.*)|)\\=.*" }, { "type": "object", "properties": { "title": { "oneOf": [ {"type": "string"}, {"type": "number"} ] }, "skip": { "type": "boolean" }, "show": { "type": "boolean" }, "description": { "type": "string" }, "params": { "$ref": "#/definitions/GridParams" } }, "required": ["title", "params"] } ] }, "Grid": { "type": "object", "additionalProperties": false, "properties": { "title": { "type": "string" }, "author": { "type": "string" }, "description": { "type": "string" }, "params": { "$ref": "#/definitions/GridParams" }, "format": { "type": "string", "enum": ["png", "jpg", "webp"] } }, "required": [ "author", "description", "format", "title" ], "title": "Grid" }, "GridParams": { "type": "object", "additionalProperties": false, "properties": { "Sampler": { "type": "string" }, "sampler": { "type": "string" }, "Model": { "type": "string" }, "model": { "type": "string" }, "VAE": { "type": "string" }, "vae": { "type": "string" }, "Prompt": { "type": "string" }, "prompt": { "type": "string" }, "NegativePrompt": { "type": "string" }, "negativeprompt": { "type": "string" }, "Negative Prompt": { "type": "string" }, "negative prompt": { "type": "string" }, "PromptReplace": { "type": "string" }, "promptreplace": { "type": "string" }, "Prompt Replace": { "type": "string" }, "prompt replace": { "type": "string" }, "Prompt Replace": { "type": "string" }, "prompt replace": { "type": "string" }, "Seed": { "type": "integer" }, "seed": { "type": "integer" }, "Steps": { "type": "integer" }, "steps": { "type": "integer" }, "CFGScale": { "type": "number" }, "cfgscale": { "type": "number" }, "CFG Scale": { "type": "number" }, "cfg scale": { "type": "number" }, "CFGscale": { "type": "number" }, "CFG scale": { "type": "number" }, "Width": { "type": "integer" }, "width": { "type": "integer" }, "Height": { "type": "integer" }, "height": { "type": "integer" }, "OutWidth": { "type": "integer" }, "outwidth": { "type": "integer" }, "Out Width": { "type": "integer" }, "out width": { "type": "integer" }, "OutHeight": { "type": "integer" }, "outheight": { "type": "integer" }, "Out Height": { "type": "integer" }, "out height": { "type": "integer" }, "ClipSkip": { "type": "integer" }, "clipskip": { "type": "integer" }, "Clip Skip": { "type": "integer" }, "clip skip": { "type": "integer" }, "VarSeed": { "type": "integer" }, "varseed": { "type": "integer" }, "Var Seed": { "type": "integer" }, "var seed": { "type": "integer" }, "VarStrength": { "type": "number" }, "varstrength": { "type": "number" }, "Var Strength": { "type": "number" }, "var strength": { "type": "number" }, "CodeFormerWeight": { "type": "number" }, "codeformerweight": { "type": "number" }, "CodeFormer Weight": { "type": "number" }, "codeformer weight": { "type": "number" }, "Denoising": { "type": "number" }, "denoising": { "type": "number" }, "ETA": { "type": "number" }, "eta": { "type": "number" }, "ETANoiseSeedDelta": { "type": "integer" }, "etanoiseseeddelta": { "type": "integer" }, "ETA Noise Seed Delta": { "type": "integer" }, "eta noise seed delta": { "type": "integer" }, "SigmaChurn": { "type": "number" }, "sigmachurn": { "type": "number" }, "Sigma Churn": { "type": "number" }, "sigma churn": { "type": "number" }, "SigmaTmin": { "type": "number" }, "sigmatmin": { "type": "number" }, "Sigma Tmin": { "type": "number" }, "sigma tmin": { "type": "number" }, "SigmaTmax": { "type": "number" }, "sigmatmax": { "type": "number" }, "Sigma Tmax": { "type": "number" }, "sigma tmax": { "type": "number" }, "SigmaNoise": { "type": "number" }, "sigmanoise": { "type": "number" }, "Sigma Noise": { "type": "number" }, "sigma noise": { "type": "number" }, "Tiling": { "type": "boolean" }, "tiling": { "type": "boolean" }, "ImageMaskWeight": { "type": "number" }, "imagemaskweight": { "type": "number" }, "Image Mask Weight": { "type": "number" }, "image mask weight": { "type": "number" }, "EnableHighresFix": { "type": "boolean" }, "enablehighresfix": { "type": "boolean" }, "Enable Highres Fix": { "type": "boolean" }, "enable highres fix": { "type": "boolean" }, "HighresScale": { "type": "number" }, "highresscale": { "type": "number" }, "Highres Scale": { "type": "number" }, "highres scale": { "type": "number" }, "HighresSteps": { "type": "integer" }, "highressteps": { "type": "integer" }, "Highres Steps": { "type": "integer" }, "highres steps": { "type": "integer" }, "HighresUpscaler": { "type": "string" }, "highresupscaler": { "type": "string" }, "Highres Upscaler": { "type": "string" }, "highres upscaler": { "type": "string" }, "HighresResizeWidth": { "type": "integer" }, "highresresizewidth": { "type": "integer" }, "Highres Resize Width": { "type": "integer" }, "highres resize width": { "type": "integer" }, "HighresResizeHeight": { "type": "integer" }, "highresresizeheight": { "type": "integer" }, "Highres Resize Height": { "type": "integer" }, "highres resize height": { "type": "integer" }, "HighresUpscaleToWidth": { "type": "integer" }, "highresupscaletowidth": { "type": "integer" }, "Highres Upscale To Width": { "type": "integer" }, "highres upscale to width": { "type": "integer" }, "HighresUpscaleToHeight": { "type": "integer" }, "highresupscaletoheight": { "type": "integer" }, "Highres Upscale To Height": { "type": "integer" }, "highres upscale to height": { "type": "integer" }, "RestoreFaces": { "oneOf": [{ "type" : "boolean"}, { "type": "string", "enum": ["GFPGan", "CodeFormer", "true", "false", "gfpgan", "codeformer"] }]}, "Restore Faces": { "oneOf": [{ "type" : "boolean"}, { "type": "string", "enum": ["GFPGan", "CodeFormer", "true", "false", "gfpgan", "codeformer"] }]}, "restorefaces": { "oneOf": [{ "type" : "boolean"}, { "type": "string", "enum": ["GFPGan", "CodeFormer", "true", "false", "gfpgan", "codeformer"] }]}, "restore faces": { "oneOf": [{ "type" : "boolean"}, { "type": "string", "enum": ["GFPGan", "CodeFormer", "true", "false", "gfpgan", "codeformer"] }]} }, "title": "GridParams" } } } ================================================ FILE: assets/images/put-usable-images-here.txt ================================================ ================================================ FILE: assets/jsgif.js ================================================ /** * This class lets you encode animated GIF files * Base class : http://www.java2s.com/Code/Java/2D-Graphics-GUI/AnimatedGifEncoder.htm * @author Kevin Weiner (original Java version - kweiner@fmsware.com) * @author Thibault Imbert (AS3 version - bytearray.org) * @author Kevin Kwok (JavaScript version - https://github.com/antimatter15/jsgif) * @version 0.1 AS3 implementation */ GIFEncoder = function() { for (var i = 0, chr = {}; i < 256; i++) chr[i] = String.fromCharCode(i); function ByteArray() { this.bin = []; } ByteArray.prototype.getData = function() { for (var v = '', l = this.bin.length, i = 0; i < l; i++) v += chr[this.bin[i]]; return v; }; ByteArray.prototype.writeByte = function(val) { this.bin.push(val); }; ByteArray.prototype.writeUTFBytes = function(string) { for (var l = string.length, i = 0; i < l; i++) this.writeByte(string.charCodeAt(i)); }; ByteArray.prototype.writeBytes = function(array, offset, length) { for (var l = length || array.length, i = offset || 0; i < l; i++) this.writeByte(array[i]); }; var exports = {}; var width; // image size var height; var transparent = null; // transparent color if given var transIndex; // transparent index in color table var repeat = -1; // no repeat var delay = 0; // frame delay (hundredths) var started = false; // ready to output frames var out; var image; // current frame var pixels; // BGR byte array from frame var indexedPixels; // converted frame indexed to palette var colorDepth; // number of bit planes var colorTab; // RGB palette var usedEntry = []; // active palette entries var palSize = 7; // color table size (bits-1) var dispose = -1; // disposal code (-1 = use default) var closeStream = false; // close stream when finished var firstFrame = true; var sizeSet = false; // if false, get size from first frame var sample = 10; // default sample interval for quantizer var comment = "Generated by jsgif (https://github.com/antimatter15/jsgif/)"; // default comment for generated gif /** * Sets the delay time between each frame, or changes it for subsequent frames * (applies to last frame added) * int delay time in milliseconds * @param ms */ var setDelay = exports.setDelay = function setDelay(ms) { delay = Math.round(ms / 10); }; /** * Sets the GIF frame disposal code for the last added frame and any * * subsequent frames. Default is 0 if no transparent color has been set, * otherwise 2. * @param code * int disposal code. */ var setDispose = exports.setDispose = function setDispose(code) { if (code >= 0) dispose = code; }; /** * Sets the number of times the set of GIF frames should be played. Default is * 1; 0 means play indefinitely. Must be invoked before the first image is * added. * * @param iter * int number of iterations. * @return */ var setRepeat = exports.setRepeat = function setRepeat(iter) { if (iter >= 0) repeat = iter; }; /** * Sets the transparent color for the last added frame and any subsequent * frames. Since all colors are subject to modification in the quantization * process, the color in the final palette for each frame closest to the given * color becomes the transparent color for that frame. May be set to null to * indicate no transparent color. * @param * Color to be treated as transparent on display. */ var setTransparent = exports.setTransparent = function setTransparent(c) { transparent = c; }; /** * Sets the comment for the block comment * @param * string to be insterted as comment */ var setComment = exports.setComment = function setComment(c) { comment = c; }; /** * The addFrame method takes an incoming BitmapData object to create each frames * @param * BitmapData object to be treated as a GIF's frame */ var addFrame = exports.addFrame = function addFrame(im, is_imageData) { if ((im === null) || !started || out === null) { throw new Error("Please call start method before calling addFrame"); } var ok = true; try { if (!is_imageData) { image = im.getImageData(0, 0, im.canvas.width, im.canvas.height).data; if (!sizeSet) setSize(im.canvas.width, im.canvas.height); } else { if(im instanceof ImageData) { image = im.data; if(!sizeset || width!=im.width || height!=im.height) { setSize(im.width,im.height); } else { } } else if(im instanceof Uint8ClampedArray) { if(im.length==(width*height*4)) { image=im; } else { console.log("Please set the correct size: ImageData length mismatch"); ok=false; } } else { console.log("Please provide correct input"); ok=false; } } getImagePixels(); // convert to correct format if necessary analyzePixels(); // build color table & map pixels if (firstFrame) { writeLSD(); // logical screen descriptior writePalette(); // global color table if (repeat >= 0) { // use NS app extension to indicate reps writeNetscapeExt(); } } writeGraphicCtrlExt(); // write graphic control extension if (comment !== '') { writeCommentExt(); // write comment extension } writeImageDesc(); // image descriptor if (!firstFrame) writePalette(); // local color table writePixels(); // encode and write pixel data firstFrame = false; } catch (e) { ok = false; } return ok; }; /** * @description: Downloads the encoded gif with the given name * No need of any conversion from the stream data (out) to base64 * Solves the issue of large file sizes when there are more frames * and does not involve in creation of any temporary data in the process * so no wastage of memory, and speeds up the process of downloading * to just calling this function. * @parameter {String} filename filename used for downloading the gif */ var download = exports.download = function download(filename) { if(out===null || closeStream==false) { console.log("Please call start method and add frames and call finish method before calling download"); } else { filename= filename !== undefined ? ( filename.endsWith(".gif")? filename: filename+".gif" ): "download.gif"; var templink = document.createElement("a"); templink.download=filename; templink.href= URL.createObjectURL(new Blob([new Uint8Array(out.bin)], {type : "image/gif" } )); templink.click(); } } /** * Adds final trailer to the GIF stream, if you don't call the finish method * the GIF stream will not be valid. */ var finish = exports.finish = function finish() { if (!started) return false; var ok = true; started = false; try { out.writeByte(0x3b); // gif trailer closeStream=true; } catch (e) { ok = false; } return ok; }; /** * Resets some members so that a new stream can be started. * This method is actually called by the start method */ var reset = function reset() { // reset for subsequent use transIndex = 0; image = null; pixels = null; indexedPixels = null; colorTab = null; closeStream = false; firstFrame = true; }; /** * * Sets frame rate in frames per second. Equivalent to * setDelay(1000/fps). * @param fps * float frame rate (frames per second) */ var setFrameRate = exports.setFrameRate = function setFrameRate(fps) { if (fps != 0xf) delay = Math.round(100 / fps); }; /** * Sets quality of color quantization (conversion of images to the maximum 256 * colors allowed by the GIF specification). Lower values (minimum = 1) * produce better colors, but slow processing significantly. 10 is the * default, and produces good color mapping at reasonable speeds. Values * greater than 20 do not yield significant improvements in speed. * @param quality * int greater than 0. * @return */ var setQuality = exports.setQuality = function setQuality(quality) { if (quality < 1) quality = 1; sample = quality; }; /** * Sets the GIF frame size. The default size is the size of the first frame * added if this method is not invoked. * @param w * int frame width. * @param h * int frame width. */ var setSize = exports.setSize = function setSize(w, h) { if (started && !firstFrame) return; width = w; height = h; if (width < 1) width = 320; if (height < 1) height = 240; sizeSet = true; }; /** * Initiates GIF file creation on the given stream. * @param os * OutputStream on which GIF images are written. * @return false if initial write failed. */ var start = exports.start = function start() { reset(); var ok = true; closeStream = false; out = new ByteArray(); try { out.writeUTFBytes("GIF89a"); // header } catch (e) { ok = false; } return started = ok; }; var cont = exports.cont = function cont() { reset(); var ok = true; closeStream = false; out = new ByteArray(); return started = ok; }; /** * Analyzes image colors and creates color map. */ var analyzePixels = function analyzePixels() { var len = pixels.length; var nPix = len / 3; indexedPixels = []; var nq = new NeuQuant(pixels, len, sample); // initialize quantizer colorTab = nq.process(); // create reduced palette // map image pixels to new palette var k = 0; for (var j = 0; j < nPix; j++) { var index = nq.map(pixels[k++] & 0xff, pixels[k++] & 0xff, pixels[k++] & 0xff); usedEntry[index] = true; indexedPixels[j] = index; } pixels = null; colorDepth = 8; palSize = 7; // get closest match to transparent color if specified if (transparent !== null) { transIndex = findClosest(transparent); } }; /** * Returns index of palette color closest to c */ var findClosest = function findClosest(c) { if (colorTab === null) return -1; var r = (c & 0xFF0000) >> 16; var g = (c & 0x00FF00) >> 8; var b = (c & 0x0000FF); var minpos = 0; var dmin = 256 * 256 * 256; var len = colorTab.length; for (var i = 0; i < len;) { var dr = r - (colorTab[i++] & 0xff); var dg = g - (colorTab[i++] & 0xff); var db = b - (colorTab[i] & 0xff); var d = dr * dr + dg * dg + db * db; var index = i / 3; if (usedEntry[index] && (d < dmin)) { dmin = d; minpos = index; } i++; } return minpos; }; /** * Extracts image pixels into byte array "pixels */ var getImagePixels = function getImagePixels() { var w = width; var h = height; pixels = []; var data = image; var count = 0; for (var i = 0; i < h; i++) { for (var j = 0; j < w; j++) { var b = (i * w * 4) + j * 4; pixels[count++] = data[b]; pixels[count++] = data[b + 1]; pixels[count++] = data[b + 2]; } } }; /** * Writes Graphic Control Extension */ var writeGraphicCtrlExt = function writeGraphicCtrlExt() { out.writeByte(0x21); // extension introducer out.writeByte(0xf9); // GCE label out.writeByte(4); // data block size var transp; var disp; if (transparent === null) { transp = 0; disp = 0; // dispose = no action } else { transp = 1; disp = 2; // force clear if using transparent color } if (dispose >= 0) { disp = dispose & 7; // user override } disp <<= 2; // packed fields out.writeByte(0 | // 1:3 reserved disp | // 4:6 disposal 0 | // 7 user input - 0 = none transp); // 8 transparency flag WriteShort(delay); // delay x 1/100 sec out.writeByte(transIndex); // transparent color index out.writeByte(0); // block terminator }; /** * Writes Comment Extention */ var writeCommentExt = function writeCommentExt() { out.writeByte(0x21); // extension introducer out.writeByte(0xfe); // comment label out.writeByte(comment.length); // Block Size (s) out.writeUTFBytes(comment); out.writeByte(0); // block terminator }; /** * Writes Image Descriptor */ var writeImageDesc = function writeImageDesc() { out.writeByte(0x2c); // image separator WriteShort(0); // image position x,y = 0,0 WriteShort(0); WriteShort(width); // image size WriteShort(height); // packed fields if (firstFrame) { // no LCT - GCT is used for first (or only) frame out.writeByte(0); } else { // specify normal LCT out.writeByte(0x80 | // 1 local color table 1=yes 0 | // 2 interlace - 0=no 0 | // 3 sorted - 0=no 0 | // 4-5 reserved palSize); // 6-8 size of color table } }; /** * Writes Logical Screen Descriptor */ var writeLSD = function writeLSD() { // logical screen size WriteShort(width); WriteShort(height); // packed fields out.writeByte((0x80 | // 1 : global color table flag = 1 (gct used) 0x70 | // 2-4 : color resolution = 7 0x00 | // 5 : gct sort flag = 0 palSize)); // 6-8 : gct size out.writeByte(0); // background color index out.writeByte(0); // pixel aspect ratio - assume 1:1 }; /** * Writes Netscape application extension to define repeat count. */ var writeNetscapeExt = function writeNetscapeExt() { out.writeByte(0x21); // extension introducer out.writeByte(0xff); // app extension label out.writeByte(11); // block size out.writeUTFBytes("NETSCAPE" + "2.0"); // app id + auth code out.writeByte(3); // sub-block size out.writeByte(1); // loop sub-block id WriteShort(repeat); // loop count (extra iterations, 0=repeat forever) out.writeByte(0); // block terminator }; /** * Writes color table */ var writePalette = function writePalette() { out.writeBytes(colorTab); var n = (3 * 256) - colorTab.length; for (var i = 0; i < n; i++) out.writeByte(0); }; var WriteShort = function WriteShort(pValue) { out.writeByte(pValue & 0xFF); out.writeByte((pValue >> 8) & 0xFF); }; /** * Encodes and writes pixel data */ var writePixels = function writePixels() { var myencoder = new LZWEncoder(width, height, indexedPixels, colorDepth); myencoder.encode(out); }; /** * Retrieves the GIF stream */ var stream = exports.stream = function stream() { return out; }; var setProperties = exports.setProperties = function setProperties(has_start, is_first) { started = has_start; firstFrame = is_first; }; return exports; }; /** * This class handles LZW encoding * Adapted from Jef Poskanzer's Java port by way of J. M. G. Elliott. * @author Kevin Weiner (original Java version - kweiner@fmsware.com) * @author Thibault Imbert (AS3 version - bytearray.org) * @author Kevin Kwok (JavaScript version - https://github.com/antimatter15/jsgif) * @version 0.1 AS3 implementation */ LZWEncoder = function() { var exports = {}; var EOF = -1; var imgW; var imgH; var pixAry; var initCodeSize; var remaining; var curPixel; // GIFCOMPR.C - GIF Image compression routines // Lempel-Ziv compression based on 'compress'. GIF modifications by // David Rowley (mgardi@watdcsu.waterloo.edu) // General DEFINEs var BITS = 12; var HSIZE = 5003; // 80% occupancy // GIF Image compression - modified 'compress' // Based on: compress.c - File compression ala IEEE Computer, June 1984. // By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas) // Jim McKie (decvax!mcvax!jim) // Steve Davies (decvax!vax135!petsd!peora!srd) // Ken Turkowski (decvax!decwrl!turtlevax!ken) // James A. Woods (decvax!ihnp4!ames!jaw) // Joe Orost (decvax!vax135!petsd!joe) var n_bits; // number of bits/code var maxbits = BITS; // user settable max # bits/code var maxcode; // maximum code, given n_bits var maxmaxcode = 1 << BITS; // should NEVER generate this code var htab = []; var codetab = []; var hsize = HSIZE; // for dynamic table sizing var free_ent = 0; // first unused entry // block compression parameters -- after all codes are used up, // and compression rate changes, start over. var clear_flg = false; // Algorithm: use open addressing double hashing (no chaining) on the // prefix code / next character combination. We do a variant of Knuth's // algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime // secondary probe. Here, the modular division first probe is gives way // to a faster exclusive-or manipulation. Also do block compression with // an adaptive reset, whereby the code table is cleared when the compression // ratio decreases, but after the table fills. The variable-length output // codes are re-sized at this point, and a special CLEAR code is generated // for the decompressor. Late addition: construct the table according to // file size for noticeable speed improvement on small files. Please direct // questions about this implementation to ames!jaw. var g_init_bits; var ClearCode; var EOFCode; // output // Output the given code. // Inputs: // code: A n_bits-bit integer. If == -1, then EOF. This assumes // that n_bits =< wordsize - 1. // Outputs: // Outputs code to the file. // Assumptions: // Chars are 8 bits long. // Algorithm: // Maintain a BITS character long buffer (so that 8 codes will // fit in it exactly). Use the VAX insv instruction to insert each // code in turn. When the buffer fills up empty it and start over. var cur_accum = 0; var cur_bits = 0; var masks = [0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF]; // Number of characters so far in this 'packet' var a_count; // Define the storage for the packet accumulator var accum = []; var LZWEncoder = exports.LZWEncoder = function LZWEncoder(width, height, pixels, color_depth) { imgW = width; imgH = height; pixAry = pixels; initCodeSize = Math.max(2, color_depth); }; // Add a character to the end of the current packet, and if it is 254 // characters, flush the packet to disk. var char_out = function char_out(c, outs) { accum[a_count++] = c; if (a_count >= 254) flush_char(outs); }; // Clear out the hash table // table clear for block compress var cl_block = function cl_block(outs) { cl_hash(hsize); free_ent = ClearCode + 2; clear_flg = true; output(ClearCode, outs); }; // reset code table var cl_hash = function cl_hash(hsize) { for (var i = 0; i < hsize; ++i) htab[i] = -1; }; var compress = exports.compress = function compress(init_bits, outs) { var fcode; var i; /* = 0 */ var c; var ent; var disp; var hsize_reg; var hshift; // Set up the globals: g_init_bits - initial number of bits g_init_bits = init_bits; // Set up the necessary values clear_flg = false; n_bits = g_init_bits; maxcode = MAXCODE(n_bits); ClearCode = 1 << (init_bits - 1); EOFCode = ClearCode + 1; free_ent = ClearCode + 2; a_count = 0; // clear packet ent = nextPixel(); hshift = 0; for (fcode = hsize; fcode < 65536; fcode *= 2) ++hshift; hshift = 8 - hshift; // set hash code range bound hsize_reg = hsize; cl_hash(hsize_reg); // clear hash table output(ClearCode, outs); outer_loop: while ((c = nextPixel()) != EOF) { fcode = (c << maxbits) + ent; i = (c << hshift) ^ ent; // xor hashing if (htab[i] == fcode) { ent = codetab[i]; continue; } else if (htab[i] >= 0) { // non-empty slot disp = hsize_reg - i; // secondary hash (after G. Knott) if (i === 0) disp = 1; do { if ((i -= disp) < 0) i += hsize_reg; if (htab[i] == fcode) { ent = codetab[i]; continue outer_loop; } } while (htab[i] >= 0); } output(ent, outs); ent = c; if (free_ent < maxmaxcode) { codetab[i] = free_ent++; // code -> hashtable htab[i] = fcode; } else cl_block(outs); } // Put out the final code. output(ent, outs); output(EOFCode, outs); }; // ---------------------------------------------------------------------------- var encode = exports.encode = function encode(os) { os.writeByte(initCodeSize); // write "initial code size" byte remaining = imgW * imgH; // reset navigation variables curPixel = 0; compress(initCodeSize + 1, os); // compress and write the pixel data os.writeByte(0); // write block terminator }; // Flush the packet to disk, and reset the accumulator var flush_char = function flush_char(outs) { if (a_count > 0) { outs.writeByte(a_count); outs.writeBytes(accum, 0, a_count); a_count = 0; } }; var MAXCODE = function MAXCODE(n_bits) { return (1 << n_bits) - 1; }; // ---------------------------------------------------------------------------- // Return the next pixel from the image // ---------------------------------------------------------------------------- var nextPixel = function nextPixel() { if (remaining === 0) return EOF; --remaining; var pix = pixAry[curPixel++]; return pix & 0xff; }; var output = function output(code, outs) { cur_accum &= masks[cur_bits]; if (cur_bits > 0) cur_accum |= (code << cur_bits); else cur_accum = code; cur_bits += n_bits; while (cur_bits >= 8) { char_out((cur_accum & 0xff), outs); cur_accum >>= 8; cur_bits -= 8; } // If the next entry is going to be too big for the code size, // then increase it, if possible. if (free_ent > maxcode || clear_flg) { if (clear_flg) { maxcode = MAXCODE(n_bits = g_init_bits); clear_flg = false; } else { ++n_bits; if (n_bits == maxbits) maxcode = maxmaxcode; else maxcode = MAXCODE(n_bits); } } if (code == EOFCode) { // At EOF, write the rest of the buffer. while (cur_bits > 0) { char_out((cur_accum & 0xff), outs); cur_accum >>= 8; cur_bits -= 8; } flush_char(outs); } }; LZWEncoder.apply(this, arguments); return exports; }; /* * NeuQuant Neural-Net Quantization Algorithm * ------------------------------------------ * * Copyright (c) 1994 Anthony Dekker * * NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994. See * "Kohonen neural networks for optimal colour quantization" in "Network: * Computation in Neural Systems" Vol. 5 (1994) pp 351-367. for a discussion of * the algorithm. * * Any party obtaining a copy of these files from the author, directly or * indirectly, is granted, free of charge, a full and unrestricted irrevocable, * world-wide, paid up, royalty-free, nonexclusive right and license to deal in * this software and documentation files (the "Software"), including without * limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons who * receive copies from any such party to do so, with the only requirement being * that this copyright notice remain intact. */ /* * This class handles Neural-Net quantization algorithm * @author Kevin Weiner (original Java version - kweiner@fmsware.com) * @author Thibault Imbert (AS3 version - bytearray.org) * @author Kevin Kwok (JavaScript version - https://github.com/antimatter15/jsgif) * @version 0.1 AS3 implementation */ NeuQuant = function() { var exports = {}; var netsize = 256; /* number of colours used */ /* four primes near 500 - assume no image has a length so large */ /* that it is divisible by all four primes */ var prime1 = 499; var prime2 = 491; var prime3 = 487; var prime4 = 503; var minpicturebytes = (3 * prime4); /* minimum size for input image */ /* * Program Skeleton ---------------- [select samplefac in range 1..30] [read * image from input file] pic = (unsigned char*) malloc(3*width*height); * initnet(pic,3*width*height,samplefac); learn(); unbiasnet(); [write output * image header, using writecolourmap(f)] inxbuild(); write output image using * inxsearch(b,g,r) */ /* * Network Definitions ------------------- */ var maxnetpos = (netsize - 1); var netbiasshift = 4; /* bias for colour values */ var ncycles = 100; /* no. of learning cycles */ /* defs for freq and bias */ var intbiasshift = 16; /* bias for fractions */ var intbias = (1 << intbiasshift); var gammashift = 10; /* gamma = 1024 */ var gamma = (1 << gammashift); var betashift = 10; var beta = (intbias >> betashift); /* beta = 1/1024 */ var betagamma = (intbias << (gammashift - betashift)); /* defs for decreasing radius factor */ var initrad = (netsize >> 3); /* for 256 cols, radius starts */ var radiusbiasshift = 6; /* at 32.0 biased by 6 bits */ var radiusbias = (1 << radiusbiasshift); var initradius = (initrad * radiusbias); /* and decreases by a */ var radiusdec = 30; /* factor of 1/30 each cycle */ /* defs for decreasing alpha factor */ var alphabiasshift = 10; /* alpha starts at 1.0 */ var initalpha = (1 << alphabiasshift); var alphadec; /* biased by 10 bits */ /* radbias and alpharadbias used for radpower calculation */ var radbiasshift = 8; var radbias = (1 << radbiasshift); var alpharadbshift = (alphabiasshift + radbiasshift); var alpharadbias = (1 << alpharadbshift); /* * Types and Global Variables -------------------------- */ var thepicture; /* the input image itself */ var lengthcount; /* lengthcount = H*W*3 */ var samplefac; /* sampling factor 1..30 */ // typedef int pixel[4]; /* BGRc */ var network; /* the network itself - [netsize][4] */ var netindex = []; /* for network lookup - really 256 */ var bias = []; /* bias and freq arrays for learning */ var freq = []; var radpower = []; var NeuQuant = exports.NeuQuant = function NeuQuant(thepic, len, sample) { var i; var p; thepicture = thepic; lengthcount = len; samplefac = sample; network = new Array(netsize); for (i = 0; i < netsize; i++) { network[i] = new Array(4); p = network[i]; p[0] = p[1] = p[2] = (i << (netbiasshift + 8)) / netsize; freq[i] = intbias / netsize; /* 1/netsize */ bias[i] = 0; } }; var colorMap = function colorMap() { var map = []; var index = new Array(netsize); for (var i = 0; i < netsize; i++) index[network[i][3]] = i; var k = 0; for (var l = 0; l < netsize; l++) { var j = index[l]; map[k++] = (network[j][0]); map[k++] = (network[j][1]); map[k++] = (network[j][2]); } return map; }; /* * Insertion sort of network and building of netindex[0..255] (to do after * unbias) * ------------------------------------------------------------------------------- */ var inxbuild = function inxbuild() { var i; var j; var smallpos; var smallval; var p; var q; var previouscol; var startpos; previouscol = 0; startpos = 0; for (i = 0; i < netsize; i++) { p = network[i]; smallpos = i; smallval = p[1]; /* index on g */ /* find smallest in i..netsize-1 */ for (j = i + 1; j < netsize; j++) { q = network[j]; if (q[1] < smallval) { /* index on g */ smallpos = j; smallval = q[1]; /* index on g */ } } q = network[smallpos]; /* swap p (i) and q (smallpos) entries */ if (i != smallpos) { j = q[0]; q[0] = p[0]; p[0] = j; j = q[1]; q[1] = p[1]; p[1] = j; j = q[2]; q[2] = p[2]; p[2] = j; j = q[3]; q[3] = p[3]; p[3] = j; } /* smallval entry is now in position i */ if (smallval != previouscol) { netindex[previouscol] = (startpos + i) >> 1; for (j = previouscol + 1; j < smallval; j++) netindex[j] = i; previouscol = smallval; startpos = i; } } netindex[previouscol] = (startpos + maxnetpos) >> 1; for (j = previouscol + 1; j < 256; j++) netindex[j] = maxnetpos; /* really 256 */ }; /* * Main Learning Loop ------------------ */ var learn = function learn() { var i; var j; var b; var g; var r; var radius; var rad; var alpha; var step; var delta; var samplepixels; var p; var pix; var lim; if (lengthcount < minpicturebytes) samplefac = 1; alphadec = 30 + ((samplefac - 1) / 3); p = thepicture; pix = 0; lim = lengthcount; samplepixels = lengthcount / (3 * samplefac); delta = (samplepixels / ncycles) | 0; alpha = initalpha; radius = initradius; rad = radius >> radiusbiasshift; if (rad <= 1) rad = 0; for (i = 0; i < rad; i++) radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad)); if (lengthcount < minpicturebytes) step = 3; else if ((lengthcount % prime1) !== 0) step = 3 * prime1; else { if ((lengthcount % prime2) !== 0) step = 3 * prime2; else { if ((lengthcount % prime3) !== 0) step = 3 * prime3; else step = 3 * prime4; } } i = 0; while (i < samplepixels) { b = (p[pix + 0] & 0xff) << netbiasshift; g = (p[pix + 1] & 0xff) << netbiasshift; r = (p[pix + 2] & 0xff) << netbiasshift; j = contest(b, g, r); altersingle(alpha, j, b, g, r); if (rad !== 0) alterneigh(rad, j, b, g, r); /* alter neighbours */ pix += step; if (pix >= lim) pix -= lengthcount; i++; if (delta === 0) delta = 1; if (i % delta === 0) { alpha -= alpha / alphadec; radius -= radius / radiusdec; rad = radius >> radiusbiasshift; if (rad <= 1) rad = 0; for (j = 0; j < rad; j++) radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad)); } } }; /* ** Search for BGR values 0..255 (after net is unbiased) and return colour * index * ---------------------------------------------------------------------------- */ var map = exports.map = function map(b, g, r) { var i; var j; var dist; var a; var bestd; var p; var best; bestd = 1000; /* biggest possible dist is 256*3 */ best = -1; i = netindex[g]; /* index on g */ j = i - 1; /* start at netindex[g] and work outwards */ while ((i < netsize) || (j >= 0)) { if (i < netsize) { p = network[i]; dist = p[1] - g; /* inx key */ if (dist >= bestd) i = netsize; /* stop iter */ else { i++; if (dist < 0) dist = -dist; a = p[0] - b; if (a < 0) a = -a; dist += a; if (dist < bestd) { a = p[2] - r; if (a < 0) a = -a; dist += a; if (dist < bestd) { bestd = dist; best = p[3]; } } } } if (j >= 0) { p = network[j]; dist = g - p[1]; /* inx key - reverse dif */ if (dist >= bestd) j = -1; /* stop iter */ else { j--; if (dist < 0) dist = -dist; a = p[0] - b; if (a < 0) a = -a; dist += a; if (dist < bestd) { a = p[2] - r; if (a < 0) a = -a; dist += a; if (dist < bestd) { bestd = dist; best = p[3]; } } } } } return (best); }; var process = exports.process = function process() { learn(); unbiasnet(); inxbuild(); return colorMap(); }; /* * Unbias network to give byte values 0..255 and record position i to prepare * for sort * ----------------------------------------------------------------------------------- */ var unbiasnet = function unbiasnet() { var i; var j; for (i = 0; i < netsize; i++) { network[i][0] >>= netbiasshift; network[i][1] >>= netbiasshift; network[i][2] >>= netbiasshift; network[i][3] = i; /* record colour no */ } }; /* * Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in * radpower[|i-j|] * --------------------------------------------------------------------------------- */ var alterneigh = function alterneigh(rad, i, b, g, r) { var j; var k; var lo; var hi; var a; var m; var p; lo = i - rad; if (lo < -1) lo = -1; hi = i + rad; if (hi > netsize) hi = netsize; j = i + 1; k = i - 1; m = 1; while ((j < hi) || (k > lo)) { a = radpower[m++]; if (j < hi) { p = network[j++]; try { p[0] -= (a * (p[0] - b)) / alpharadbias; p[1] -= (a * (p[1] - g)) / alpharadbias; p[2] -= (a * (p[2] - r)) / alpharadbias; } catch (e) {} // prevents 1.3 miscompilation } if (k > lo) { p = network[k--]; try { p[0] -= (a * (p[0] - b)) / alpharadbias; p[1] -= (a * (p[1] - g)) / alpharadbias; p[2] -= (a * (p[2] - r)) / alpharadbias; } catch (e) {} } } }; /* * Move neuron i towards biased (b,g,r) by factor alpha * ---------------------------------------------------- */ var altersingle = function altersingle(alpha, i, b, g, r) { /* alter hit neuron */ var n = network[i]; n[0] -= (alpha * (n[0] - b)) / initalpha; n[1] -= (alpha * (n[1] - g)) / initalpha; n[2] -= (alpha * (n[2] - r)) / initalpha; }; /* * Search for biased BGR values ---------------------------- */ var contest = function contest(b, g, r) { /* finds closest neuron (min dist) and updates freq */ /* finds best neuron (min dist-bias) and returns position */ /* for frequently chosen neurons, freq[i] is high and bias[i] is negative */ /* bias[i] = gamma*((1/netsize)-freq[i]) */ var i; var dist; var a; var biasdist; var betafreq; var bestpos; var bestbiaspos; var bestd; var bestbiasd; var n; bestd = ~ (1 << 31); bestbiasd = bestd; bestpos = -1; bestbiaspos = bestpos; for (i = 0; i < netsize; i++) { n = network[i]; dist = n[0] - b; if (dist < 0) dist = -dist; a = n[1] - g; if (a < 0) a = -a; dist += a; a = n[2] - r; if (a < 0) a = -a; dist += a; if (dist < bestd) { bestd = dist; bestpos = i; } biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift)); if (biasdist < bestbiasd) { bestbiasd = biasdist; bestbiaspos = i; } betafreq = (freq[i] >> betashift); freq[i] -= betafreq; bias[i] += (betafreq << gammashift); } freq[bestpos] += beta; bias[bestpos] -= betagamma; return (bestbiaspos); }; NeuQuant.apply(this, arguments); return exports; }; function encode64(input) { var output = "", i = 0, l = input.length, key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", chr1, chr2, chr3, enc1, enc2, enc3, enc4; while (i < l) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) enc3 = enc4 = 64; else if (isNaN(chr3)) enc4 = 64; output = output + key.charAt(enc1) + key.charAt(enc2) + key.charAt(enc3) + key.charAt(enc4); } return output; } ================================================ FILE: assets/page.html ================================================ {TITLE}

{TITLE}

{DESCRIPTION}




Created by: {AUTHOR}
The technology that powers this page is Infinity Grid Generator, published under the MIT license by Alex 'mcmonkey' Goodwin.
This software allows users to generate pages with any content they desire. Therefore, content on this page (images, text, etc.) is the property of whoever generated this specific page.
{EXTRA_FOOTER}
Made using the Darkly Bootstrap Theme by Thomas Park, which was released under the MIT License.
Gifs are generated using JSGif, which was released under the MIT License.

================================================ FILE: assets/proc.js ================================================ /* * This file is part of Infinity Grid Generator, view the README.md at https://github.com/mcmonkeyprojects/sd-infinity-grid-generator-script for more information. */ let suppressUpdate = true; let file_extensions_alt = {}; function loadData() { let rawHash = window.location.hash; document.getElementById('x_' + rawData.axes[0].id).click(); document.getElementById('x2_none').click(); document.getElementById('y2_none').click(); let makegif_axis = document.getElementById('makegif_axis'); // rawData.ext/title/description for (var axis of rawData.axes) { // axis.id/title/description for (var val of axis.values) { // val.key/title/description/show let clicktab = getNavValTab(axis.id, val.key); clicktab.addEventListener('click', fillTable); if (!val.show) { setShowVal(axis.id, val.key, false); } } for (var prefix of ['x_', 'y_', 'x2_', 'y2_']) { document.getElementById(prefix + axis.id).addEventListener('click', fillTable); } for (var label of ['x2_none', 'y2_none']) { document.getElementById(label).addEventListener('click', fillTable); } makegif_axis.appendChild(new Option(axis.title, axis.id)); } console.log(`Loaded data for '${rawData.title}'`); document.getElementById('autoScaleImages').addEventListener('change', updateScaling); document.getElementById('stickyNavigation').addEventListener('change', toggleTopSticky); document.getElementById('stickyLabels').addEventListener('change', toggleLabelSticky); document.getElementById('toggle_nav_button').addEventListener('click', updateTitleSticky); document.getElementById('toggle_adv_button').addEventListener('click', updateTitleSticky); document.getElementById('showDescriptions').checked = rawData.defaults.show_descriptions; document.getElementById('autoScaleImages').checked = rawData.defaults.autoscale; document.getElementById('stickyNavigation').checked = rawData.defaults.sticky; document.getElementById('stickyLabels').checked = rawData.defaults.sticky_labels; document.getElementById('score_display').addEventListener('click', fillTable); document.getElementById('score_setting').style.display = typeof getScoreFor == 'undefined' ? 'none' : 'inline-block'; updateStylesToMatchInputs(); for (var axis of ['x', 'y', 'x2', 'y2']) { if (rawData.defaults[axis] != '') { document.getElementById(axis + '_' + rawData.defaults[axis]).click(); } } applyHash(rawHash); suppressUpdate = false; fillTable(); startAutoScroll(); if (rawData.will_run) { setTimeout(checkForUpdates, 5000); } } function getExtension(filePath) { if (filePath in file_extensions_alt) { return file_extensions_alt[filePath]; } return rawData.ext; } /** External callable. */ function fix_video(path) { let ext = getExtension(path); let matches = document.querySelectorAll(`img[data-img_path="${path}"]`); for (let match of matches) { if (ext != 'webm' && ext != 'mp4') { if (!match.src.endsWith(ext)) { match.src = `${path}.${ext}`; } continue; } if (match.tagName == 'VIDEO') { continue; } let video = document.createElement('video'); video.loop = true; video.muted = true; video.autoplay = true; video.classList = match.classList; video.dataset.img_path = match.dataset.img_path; video.onclick = "doPopupFor(this)"; video.onerror = "setImgPlaceholder(this)"; let source = document.createElement('source'); source.src = `${path}.${ext}`; source.type = `video/${ext}`; video.appendChild(source); match.parentElement.replaceChild(video, match); } } function updateStylesToMatchInputs() { toggleTopSticky(); toggleLabelSticky(); } function getAxisById(id) { return rawData.axes.find(axis => axis.id == id); } function getNextAxis(axes, startId) { var next = false; for (var subAxis of axes) { if (subAxis.id == startId) { next = true; } else if (next) { return subAxis; } } return null; } function getSelectedValKey(axis) { for (var subVal of axis.values) { if (window.getComputedStyle(document.getElementById('tab_' + axis.id + '__' + subVal.key)).display != 'none') { return subVal.path; } } return null; } var popoverLastImg = null; function clickRowImage(rows, x, y) { $('#image_info_modal').modal('hide'); var columns = rows[y].getElementsByTagName('td'); columns[x].getElementsByTagName('img')[0].click(); } window.addEventListener('keydown', function(kbevent) { if ($('#image_info_modal').is(':visible')) { if (kbevent.key == 'Escape') { $('#image_info_modal').modal('toggle'); kbevent.preventDefault(); kbevent.stopPropagation(); return false; } var tableElem = document.getElementById('image_table'); var rows = tableElem.getElementsByTagName('tr'); var matchedRow = null; var x = 0, y = 0; for (var row of rows) { var columns = row.getElementsByTagName('td'); for (var column of columns) { var images = column.getElementsByTagName('img'); if (images.length == 1 && images[0] == popoverLastImg) { matchedRow = row; break; } x++; } if (matchedRow != null) { break; } x = 0; y++; } if (matchedRow == null) { return; } if (kbevent.key == 'ArrowLeft') { if (x > 1) { x--; clickRowImage(rows, x, y); } } else if (kbevent.key == 'ArrowRight') { x++; var columns = matchedRow.getElementsByTagName('td'); if (columns.length > x) { clickRowImage(rows, x, y); } } else if (kbevent.key == 'ArrowUp') { if (y > 1) { y--; clickRowImage(rows, x, y); } } else if (kbevent.key == 'ArrowDown') { y++; if (rows.length > y) { clickRowImage(rows, x, y); } } else { return; } kbevent.preventDefault(); kbevent.stopPropagation(); return false; } var elem = document.activeElement; if (!elem.id.startsWith('clicktab_')) { return; } var axisId = elem.id.substring('clicktab_'.length); var splitIndex = axisId.lastIndexOf('__'); axisId = axisId.substring(0, splitIndex); var axis = getAxisById(axisId); if (kbevent.key == 'ArrowLeft') { var tabPage = document.getElementById('tablist_' + axis.id); var tabs = tabPage.getElementsByClassName('nav-link'); var newTab = clickTabAfterActiveTab(Array.from(tabs).reverse()); newTab.focus({ preventScroll: true }); } else if (kbevent.key == 'ArrowRight') { var tabPage = document.getElementById('tablist_' + axis.id); var tabs = tabPage.getElementsByClassName('nav-link'); var newTab = clickTabAfterActiveTab(tabs); newTab.focus({ preventScroll: true }); } else if (kbevent.key == 'ArrowUp') { var next = getNextAxis(Array.from(rawData.axes).reverse(), axisId); if (next != null) { var selectedKey = getSelectedValKey(next); var swapToTab = getNavValTab(next.id, selectedKey); swapToTab.focus({ preventScroll: true }); } } else if (kbevent.key == 'ArrowDown') { var next = getNextAxis(rawData.axes, axisId); if (next != null) { var selectedKey = getSelectedValKey(next); var swapToTab = getNavValTab(next.id, selectedKey); swapToTab.focus({ preventScroll: true }); } } else { return; } kbevent.preventDefault(); kbevent.stopPropagation(); return false; }, true); function escapeHtml(text) { if (typeof text != 'string') { return text; } return text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", '''); } function unescapeHtml(text) { return text.replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll(''', "'").replaceAll('&', '&'); } function canShowVal(axis, val) { return document.getElementById(`showval_${axis}__${val}`).checked; } function setShowVal(axis, val, show) { document.getElementById(`showval_${axis}__${val}`).checked = show; getNavValTab(axis, val).classList.toggle('tab_hidden', !show); } function getNavValTab(axis, val) { return document.getElementById(`clicktab_${axis}__${val}`); } function percentToRedGreen(percent) { return `color-mix(in srgb, red, green ${percent}%)`; } let scoreTrackCounter = 0; let scoreUpdates = []; let lastScoreBump = Date.now(); let scoreBumpTracker = null; let scoreMin = 0, scoreMax = 1; function getXAxisContent(x, y, xAxis, yval, x2Axis, x2val, y2Axis, y2val) { let scriptDump = document.getElementById('image_script_dump'); let imgPath = []; let index = 0; for (let subAxis of rawData.axes) { if (subAxis.id == x) { index = imgPath.length; imgPath.push(null); } else if (subAxis.id == y) { imgPath.push(yval.path); } else if (x2Axis != null && subAxis.id == x2Axis.id) { imgPath.push(x2val.path); } else if (y2Axis != null && subAxis.id == y2Axis.id) { imgPath.push(y2val.path); } else { imgPath.push(getSelectedValKey(subAxis)); } } let newContent = ''; let subInd = 0; let scoreDisplay = document.getElementById('score_display').value; for (let xVal of xAxis.values) { subInd++; if (!canShowVal(xAxis.id, xVal.key)) { continue; } imgPath[index] = xVal.path; let slashed = imgPath.join('/'); let ext = getExtension(slashed); let actualUrl = slashed + '.' + ext; let id = scoreTrackCounter++; newContent += ``; if (ext == 'mp4' || ext == 'webm') { newContent += ``; } else { newContent += `${actualUrl}`; } newContent += ''; let newScr = null; if (typeof getMetadataScriptFor != 'undefined') { newScr = document.createElement('script'); newScr.src = getMetadataScriptFor(slashed); } let doScores = scoreDisplay != 'None' && typeof getScoreFor != 'undefined'; if (doScores) { scoreUpdates.push(() => { let score = getScoreFor(slashed); if (score) { score = (score - scoreMin) / (scoreMax - scoreMin); let elem = document.getElementById(`td-img-${id}`); let color = percentToRedGreen(score * 100); let blockColor = ''; if (scoreDisplay == 'Thin Outline') { let xborder = `border-top: 2px solid ${color}; border-bottom: 2px solid ${color};`; let yborder = `border-left: 2px solid ${color}; border-right: 2px solid ${color};`; elem.getElementsByTagName('img')[0].style = `${xborder} ${yborder}`; } else if (scoreDisplay == 'Thick Bars') { elem.getElementsByTagName('img')[0].style = `border-top: 10px solid ${color}; border-left: 10px solid ${color};`; } else if (scoreDisplay == 'Heatmap') { blockColor = `color-mix(in srgb, ${color} 50%, transparent)`; } elem.firstChild.innerHTML = `
${Math.round(score * 100)}%
`; } }); } if (newScr != null) { newScr.onload = () => { setTimeout(() => { lastScoreBump = Date.now(); let ext = file_extensions_alt[slashed]; if (ext && !actualUrl.endsWith(ext)) { fix_video(slashed); } }, 1); if (scoreBumpTracker == null) { scoreBumpTracker = setInterval(() => { if (Date.now() - lastScoreBump > 300) { clearInterval(scoreBumpTracker); scoreBumpTracker = null; if (doScores) { scoreMin = 1; scoreMax = 0; for (let image of document.getElementsByClassName('table_img')) { let score = getScoreFor(image.dataset.img_path); if (score) { scoreMin = Math.min(scoreMin, score); scoreMax = Math.max(scoreMax, score); } } let upds = scoreUpdates; scoreUpdates = []; for (let update of upds) { update(); } updateScaling(); } } }, 100); } }; } if (newScr) { scriptDump.appendChild(newScr); } } return newContent; } function setImgPlaceholder(img) { if (!img.parentElement) { return; } img.onerror = undefined; img.dataset.errored_src = img.src; img.src = 'placeholder.png'; if (rawData.min_width) { img.width = rawData.min_width; img.height = rawData.min_height; } setImageScale(img, getWantedScaling()); } function optDescribe(isFirst, val) { return isFirst && val != null ? '' + escapeHtml(val.title) + '
' : (val != null ? '
' : ''); } function fillTable() { if (suppressUpdate) { return; } var x = getCurrentSelectedAxis('x'); var y = getCurrentSelectedAxis('y'); var x2 = getCurrentSelectedAxis('x2'); var y2 = getCurrentSelectedAxis('y2'); console.log('Do fill table, x=' + x + ', y=' + y + ', x2=' + x2 + ', y2=' + y2); var xAxis = getAxisById(x); var yAxis = getAxisById(y); var x2Axis = x2 == 'None' || x2 == x || x2 == y ? null : getAxisById(x2); var y2Axis = y2 == 'None' || y2 == x2 || y2 == x || y2 == y ? null : getAxisById(y2); var table = document.getElementById('image_table'); var newContent = ''; var superFirst = true; document.getElementById('image_script_dump').innerHTML = ''; for (var x2val of (x2Axis == null ? [null] : x2Axis.values)) { if (x2val != null && !canShowVal(x2Axis.id, x2val.key)) { continue; } var x2first = true; for (var val of xAxis.values) { if (!canShowVal(xAxis.id, val.key)) { continue; } newContent += `${optDescribe(x2first, x2val)}${escapeHtml(val.title)}`; x2first = false; } superFirst = !superFirst; } newContent += ''; superFirst = true; for (var y2val of (y2Axis == null ? [null] : y2Axis.values)) { if (y2val != null && !canShowVal(y2Axis.id, y2val.key)) { continue; } var y2first = true; for (var val of yAxis.values) { if (!canShowVal(yAxis.id, val.key)) { continue; } newContent += `${optDescribe(y2first, y2val)}${escapeHtml(val.title)}`; y2first = false; for (var x2val of (x2Axis == null ? [null] : x2Axis.values)) { if (x2val != null && !canShowVal(x2Axis.id, x2val.key)) { continue; } newContent += getXAxisContent(x, y, xAxis, val, x2Axis, x2val, y2Axis, y2val); } newContent += ''; if (x == y) { break; } } superFirst = !superFirst; } table.innerHTML = newContent; updateScaling(); } function getCurrentSelectedAxis(axisPrefix) { var id = document.querySelector(`input[name="${axisPrefix}_axis_selector"]:checked`).id; var index = id.indexOf('_'); return id.substring(index + 1); } function getShownItemsOfAxis(axis) { return axis.values.filter(val => canShowVal(axis.id, val.key)); } function getWantedScaling() { if (!document.getElementById('autoScaleImages').checked) { return 0; } var x = getCurrentSelectedAxis('x'); var xAxis = getAxisById(x); var count = getShownItemsOfAxis(xAxis).length; var x2 = getCurrentSelectedAxis('x2'); if (x2 != 'none') { var x2Axis = getAxisById(x2); count *= getShownItemsOfAxis(x2Axis).length; } return (90 / count); } function setImageScale(image, percent) { let heatmapper = image.parentElement.getElementsByClassName('heatmapper')[0]; if (percent == 0) { image.style.width = ''; image.style.height = ''; if (heatmapper) { heatmapper.style.width = `${image.clientWidth}px`; heatmapper.style.height = `${image.clientWidth}px`; } } else { image.style.width = percent + 'vw'; if (heatmapper) { heatmapper.style.width = percent + 'vw'; heatmapper.style.height = percent * (parseFloat(image.clientWidth) / parseFloat(image.clientHeight)) + 'vw'; } let width = image.getAttribute('width'); let height = image.getAttribute('height'); if (width != null && height != null) { // Rescale placeholders cleanly image.style.height = (percent * (parseFloat(height) / parseFloat(width))) + 'vw'; } else { image.style.height = ''; } } } function updateScaling() { let percent = getWantedScaling(); for (var image of document.getElementById('image_table').getElementsByClassName('table_img')) { setImageScale(image, percent); } updateTitleSticky(); } function toggleDescriptions() { var show = document.getElementById('showDescriptions').checked; for (var cName of ['tabval_subdiv', 'axis_table_cell']) { for (var elem of document.getElementsByClassName(cName)) { elem.classList.toggle('tab_hidden', !show); } } updateTitleSticky(); } function toggleShowAllAxis(axisId) { var axis = getAxisById(axisId); var hide = axis.values.some(val => { return canShowVal(axisId, val.key); }); for (var val of axis.values) { setShowVal(axisId, val.key, !hide); } fillTable(); } function toggleShowVal(axis, val) { var show = canShowVal(axis, val); let element = getNavValTab(axis, val); element.classList.toggle('tab_hidden', !show); if (!show && element.classList.contains('active')) { var next = [...element.parentElement.parentElement.getElementsByClassName('nav-link')].filter(e => !e.classList.contains('tab_hidden')); if (next.length > 0) { next[0].click(); } } fillTable(); } var anyRangeActive = false; function enableRange(id) { var range = document.getElementById('range_tablist_' + id); var label = document.getElementById('label_range_tablist_' + id); range.oninput = function() { anyRangeActive = true; label.innerText = (range.value / 2) + ' seconds'; }; var tabPage = document.getElementById('tablist_' + id); return { range, counter: 0, tabs: tabPage.getElementsByClassName('nav-link') }; } function clickTabAfterActiveTab(tabs) { var firstTab = null; var foundActive = false; var nextTab = Array.from(tabs).find(tab => { var isActive = tab.classList.contains('active'); var isHidden = tab.classList.contains('tab_hidden'); if (!isHidden && !isActive && !firstTab) { firstTab = tab; } if (isActive) { foundActive = true; return false; } return (foundActive && !isHidden); }) || firstTab; if (nextTab) { nextTab.click(); } return nextTab; } const timer = ms => new Promise(res => setTimeout(res, ms)); async function startAutoScroll() { var rangeSet = []; for (var axis of rawData.axes) { rangeSet.push(enableRange(axis.id)); } while (true) { await timer(500); if (!anyRangeActive) { continue; } for (var data of rangeSet) { if (data.range.value <= 0) { continue; } data.counter++; if (data.counter < data.range.value) { continue; } data.counter = 0; clickTabAfterActiveTab(data.tabs); } } } function crunchMetadata(parts) { if (!('metadata' in rawData)) { return {}; } var initialData = structuredClone(rawData.metadata); if (!initialData) { return {}; } for (var index = 0; index < parts.length; index++) { var part = parts[index]; var axis = rawData.axes[index]; var actualVal = axis.values.find(val => val.key == part); if (actualVal == null) { return { 'error': `metadata parsing failed for part ${index}: ${part}` }; } for (var [key, value] of Object.entries(actualVal.params)) { key = key.replaceAll(' ', ''); if (typeof(crunchParamHook) == 'undefined' || !crunchParamHook(initialData, key, value)) { initialData[key] = value; } } } return initialData; } function doPopupFor(img) { popoverLastImg = img; let modalElem = document.getElementById('image_info_modal'); let metaText; if (typeof getMetadataForImage != 'undefined') { metaText = getMetadataForImage(img); } else { let imgPath = img.dataset.img_path.split('/'); let metaData = crunchMetadata(imgPath); metaText = typeof(formatMetadata) == 'undefined' ? JSON.stringify(metaData) : formatMetadata(metaData); } let params = escapeHtml(metaText).replaceAll('\n', '\n
'); let text = 'Image: ' + img.alt + (params.length > 1 ? ', parameters:
' + params : '
(parameters hidden)'); modalElem.innerHTML = `