[
  {
    "path": ".github/bug_report.md",
    "content": "---\nname: Bug Report\nabout: Report that something isn't working.\nlabels: bug\n---\n\n## Description\n\n<!-- Describe the issue that you're seeing. -->\n\n### Steps to reproduce\n\n<!-- Clear steps describing how to reproduce the issue. -->\n\n### Expected result\n\n<!-- What should happen? -->\n\n### Actual result\n\n<!-- What happened? -->\n\n### Environment\n\n- OS Version:\n- Node.js version:"
  },
  {
    "path": ".github/feature_request.md",
    "content": "---\nname: Feature Request\nabout: Suggest a new idea for the project.\nlabels: enhancement\n---\n\n## Summary\n\n<!-- Brief explanation of the feature. -->\n\n### Basic example\n\n<!-- Include a basic code example. Omit this section if it's not applicable. -->\n\n### Motivation\n\n<!-- Why are we doing this? What use cases does it support? What is the expected outcome? -->\n"
  },
  {
    "path": ".gitignore",
    "content": "# Logs\n\nlogs\n_.log\nnpm-debug.log_\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log\\*\n\n# Diagnostic reports (https://nodejs.org/api/report.html)\n\nreport.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json\n\n# Runtime data\n\npids\n_.pid\n_.seed\n\\*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\n\nlib-cov\n\n# Coverage directory used by tools like istanbul\n\ncoverage\n\\*.lcov\n\n# nyc test coverage\n\n.nyc_output\n\n# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)\n\n.grunt\n\n# Bower dependency directory (https://bower.io/)\n\nbower_components\n\n# node-waf configuration\n\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\n\nbuild/Release\n\n# Dependency directories\n\nbuild/\ndist/\nnode_modules/\njspm_packages/\n\n# TypeScript v1 declaration files\n\ntypings/\n\n# TypeScript cache\n\n\\*.tsbuildinfo\n\n# Optional npm cache directory\n\n.npm\n\n# Optional eslint cache\n\n.eslintcache\n\n# Microbundle cache\n\n.rpt2_cache/\n.rts2_cache_cjs/\n.rts2_cache_es/\n.rts2_cache_umd/\n\n# Optional REPL history\n\n.node_repl_history\n\n# Output of 'npm pack'\n\n\\*.tgz\n\n# Yarn Integrity file\n\n.yarn-integrity\n\n# dotenv environment variables file\n\n.env\n.env.test\n\n# parcel-bundler cache (https://parceljs.org/)\n\n.cache\n\n# Next.js build output\n\n.next\n\n# Nuxt.js build / generate output\n\n.nuxt\ndist\n\n# Gatsby files\n\n.cache/\n\n# Comment in the public line in if your project uses Gatsby and _not_ Next.js\n\n# https://nextjs.org/blog/next-9-1#public-directory-support\n\n# public\n\n# vuepress build output\n\n.vuepress/dist\n\n# Serverless directories\n\n.serverless/\n\n# FuseBox cache\n\n.fusebox/\n\n# DynamoDB Local files\n\n.dynamodb/\n\n# TernJS port file\n\n.tern-port\n\n# OSX\n\n.DS_Store\n"
  },
  {
    "path": ".nvmrc",
    "content": "v14.18.2\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 HashLips\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Welcome to HashLips 👄\n\n![](https://github.com/HashLips/hashlips_art_engine/blob/main/logo.png)\n\nAll the code in these repos was created and explained by HashLips on the main YouTube channel.\n\nTo find out more please visit:\n\n[📺 YouTube](https://www.youtube.com/channel/UC1LV4_VQGBJHTJjEWUmy8nA)\n\n[👄 Discord](https://discord.com/invite/qh6MWhMJDN)\n\n[💬 Telegram](https://t.me/hashlipsnft)\n\n[🐦 Twitter](https://twitter.com/hashlipsnft)\n\n[ℹ️ Website](https://hashlips.online/HashLips)\n\n# HashLips Art Engine 🔥\n\n![](https://github.com/HashLips/hashlips_art_engine/blob/main/banner.png)\n\nCreate generative art by using the canvas api and node js. Before you use the generation engine, make sure you have node.js(v10.18.0) installed.\n\n## Installation 🛠️\n\nIf you are cloning the project then run this first, otherwise you can download the source code on the release page and skip this step.\n\n```sh\ngit clone https://github.com/HashLips/hashlips_art_engine.git\n```\n\nGo to the root of your folder and run this command if you have yarn installed.\n\n```sh\nyarn install\n```\n\nAlternatively you can run this command if you have node installed.\n\n```sh\nnpm install\n```\n\n## Usage ℹ️\n\nCreate your different layers as folders in the 'layers' directory, and add all the layer assets in these directories. You can name the assets anything as long as it has a rarity weight attached in the file name like so: `example element#70.png`. You can optionally change the delimiter `#` to anything you would like to use in the variable `rarityDelimiter` in the `src/config.js` file.\n\nOnce you have all your layers, go into `src/config.js` and update the `layerConfigurations` objects `layersOrder` array to be your layer folders name in order of the back layer to the front layer.\n\n_Example:_ If you were creating a portrait design, you might have a background, then a head, a mouth, eyes, eyewear, and then headwear, so your `layersOrder` would look something like this:\n\n```js\nconst layerConfigurations = [\n  {\n    growEditionSizeTo: 100,\n    layersOrder: [\n      { name: \"Head\" },\n      { name: \"Mouth\" },\n      { name: \"Eyes\" },\n      { name: \"Eyeswear\" },\n      { name: \"Headwear\" },\n    ],\n  },\n];\n```\n\nThe `name` of each layer object represents the name of the folder (in `/layers/`) that the images reside in.\n\nOptionally you can now add multiple different `layerConfigurations` to your collection. Each configuration can be unique and have different layer orders, use the same layers or introduce new ones. This gives the artist flexibility when it comes to fine tuning their collections to their needs.\n\n_Example:_ If you were creating a portrait design, you might have a background, then a head, a mouth, eyes, eyewear, and then headwear and you want to create a new race or just simple re-order the layers or even introduce new layers, then you're `layerConfigurations` and `layersOrder` would look something like this:\n\n```js\nconst layerConfigurations = [\n  {\n    // Creates up to 50 artworks\n    growEditionSizeTo: 50,\n    layersOrder: [\n      { name: \"Background\" },\n      { name: \"Head\" },\n      { name: \"Mouth\" },\n      { name: \"Eyes\" },\n      { name: \"Eyeswear\" },\n      { name: \"Headwear\" },\n    ],\n  },\n  {\n    // Creates an additional 100 artworks\n    growEditionSizeTo: 150,\n    layersOrder: [\n      { name: \"Background\" },\n      { name: \"Head\" },\n      { name: \"Eyes\" },\n      { name: \"Mouth\" },\n      { name: \"Eyeswear\" },\n      { name: \"Headwear\" },\n      { name: \"AlienHeadwear\" },\n    ],\n  },\n];\n```\n\nUpdate your `format` size, ie the outputted image size, and the `growEditionSizeTo` on each `layerConfigurations` object, which is the amount of variation outputted.\n\nYou can mix up the `layerConfigurations` order on how the images are saved by setting the variable `shuffleLayerConfigurations` in the `config.js` file to true. It is false by default and will save all images in numerical order.\n\nIf you want to have logs to debug and see what is happening when you generate images you can set the variable `debugLogs` in the `config.js` file to true. It is false by default, so you will only see general logs.\n\nIf you want to play around with different blending modes, you can add a `blend: MODE.colorBurn` field to the layersOrder `options` object.\n\nIf you need a layers to have a different opacity then you can add the `opacity: 0.7` field to the layersOrder `options` object as well.\n\nIf you want to have a layer _ignored_ in the DNA uniqueness check, you can set `bypassDNA: true` in the `options` object. This has the effect of making sure the rest of the traits are unique while not considering the `Background` Layers as traits, for example. The layers _are_ included in the final image.\n\nTo use a different metadata attribute name you can add the `displayName: \"Awesome Eye Color\"` to the `options` object. All options are optional and can be addes on the same layer if you want to.\n\nHere is an example on how you can play around with both filter fields:\n\n```js\nconst layerConfigurations = [\n  {\n    growEditionSizeTo: 5,\n    layersOrder: [\n      { name: \"Background\" , {\n        options: {\n          bypassDNA: false;\n        }\n      }},\n      { name: \"Eyeball\" },\n      {\n        name: \"Eye color\",\n        options: {\n          blend: MODE.destinationIn,\n          opacity: 0.2,\n          displayName: \"Awesome Eye Color\",\n        },\n      },\n      { name: \"Iris\" },\n      { name: \"Shine\" },\n      { name: \"Bottom lid\", options: { blend: MODE.overlay, opacity: 0.7 } },\n      { name: \"Top lid\" },\n    ],\n  },\n];\n```\n\nHere is a list of the different blending modes that you can optionally use.\n\n```js\nconst MODE = {\n  sourceOver: \"source-over\",\n  sourceIn: \"source-in\",\n  sourceOut: \"source-out\",\n  sourceAtop: \"source-out\",\n  destinationOver: \"destination-over\",\n  destinationIn: \"destination-in\",\n  destinationOut: \"destination-out\",\n  destinationAtop: \"destination-atop\",\n  lighter: \"lighter\",\n  copy: \"copy\",\n  xor: \"xor\",\n  multiply: \"multiply\",\n  screen: \"screen\",\n  overlay: \"overlay\",\n  darken: \"darken\",\n  lighten: \"lighten\",\n  colorDodge: \"color-dodge\",\n  colorBurn: \"color-burn\",\n  hardLight: \"hard-light\",\n  softLight: \"soft-light\",\n  difference: \"difference\",\n  exclusion: \"exclusion\",\n  hue: \"hue\",\n  saturation: \"saturation\",\n  color: \"color\",\n  luminosity: \"luminosity\",\n};\n```\n\nWhen you are ready, run the following command and your outputted art will be in the `build/images` directory and the json in the `build/json` directory:\n\n```sh\nnpm run build\n```\n\nor\n\n```sh\nnode index.js\n```\n\nThe program will output all the images in the `build/images` directory along with the metadata files in the `build/json` directory. Each collection will have a `_metadata.json` file that consists of all the metadata in the collection inside the `build/json` directory. The `build/json` folder also will contain all the single json files that represent each image file. The single json file of a image will look something like this:\n\n```json\n{\n  \"dna\": \"d956cdf4e460508b5ff90c21974124f68d6edc34\",\n  \"name\": \"#1\",\n  \"description\": \"This is the description of your NFT project\",\n  \"image\": \"https://hashlips/nft/1.png\",\n  \"edition\": 1,\n  \"date\": 1731990799975,\n  \"attributes\": [\n    { \"trait_type\": \"Background\", \"value\": \"Black\" },\n    { \"trait_type\": \"Eyeball\", \"value\": \"Red\" },\n    { \"trait_type\": \"Eye color\", \"value\": \"Yellow\" },\n    { \"trait_type\": \"Iris\", \"value\": \"Small\" },\n    { \"trait_type\": \"Shine\", \"value\": \"Shapes\" },\n    { \"trait_type\": \"Bottom lid\", \"value\": \"Low\" },\n    { \"trait_type\": \"Top lid\", \"value\": \"Middle\" }\n  ],\n  \"compiler\": \"HashLips Art Engine\"\n}\n```\n\nYou can also add extra metadata to each metadata file by adding your extra items, (key: value) pairs to the `extraMetadata` object variable in the `config.js` file.\n\n```js\nconst extraMetadata = {\n  creator: \"Daniel Eugene Botha\",\n};\n```\n\nIf you don't need extra metadata, simply leave the object empty. It is empty by default.\n\n```js\nconst extraMetadata = {};\n```\n\nThat's it, you're done.\n\n## Utils\n\n### Updating baseUri for IPFS and description\n\nYou might possibly want to update the baseUri and description after you have ran your collection. To update the baseUri and description simply run:\n\n```sh\nnpm run update_info\n```\n\n### Generate a preview image\n\nCreate a preview image collage of your collection, run:\n\n```sh\nnpm run preview\n```\n\n### Generate pixelated images from collection\n\nIn order to convert images into pixelated images you would need a list of images that you want to convert. So run the generator first.\n\nThen simply run this command:\n\n```sh\nnpm run pixelate\n```\n\nAll your images will be outputted in the `/build/pixel_images` directory.\nIf you want to change the ratio of the pixelation then you can update the ratio property on the `pixelFormat` object in the `src/config.js` file. The lower the number on the left, the more pixelated the image will be.\n\n```js\nconst pixelFormat = {\n  ratio: 5 / 128,\n};\n```\n\n### Generate GIF images from collection\n\nIn order to export gifs based on the layers created, you just need to set the export on the `gif` object in the `src/config.js` file to `true`. You can also play around with the `repeat`, `quality` and the `delay` of the exported gif.\n\nSetting the `repeat: -1` will produce a one time render and `repeat: 0` will loop forever.\n\n```js\nconst gif = {\n  export: true,\n  repeat: 0,\n  quality: 100,\n  delay: 500,\n};\n```\n\n### Printing rarity data (Experimental feature)\n\nTo see the percentages of each attribute across your collection, run:\n\n```sh\nnpm run rarity\n```\n\nThe output will look something like this:\n\n```sh\nTrait type: Top lid\n{\n  trait: 'High',\n  chance: '30',\n  occurrence: '3 in 20 editions (15.00 %)'\n}\n{\n  trait: 'Low',\n  chance: '20',\n  occurrence: '3 in 20 editions (15.00 %)'\n}\n{\n  trait: 'Middle',\n  chance: '50',\n  occurrence: '14 in 20 editions (70.00 %)'\n}\n```\n\nHope you create some awesome artworks with this code 👄\n"
  },
  {
    "path": "constants/blend_mode.js",
    "content": "const MODE = {\n  sourceOver: \"source-over\",\n  sourceIn: \"source-in\",\n  sourceOut: \"source-out\",\n  sourceAtop: \"source-out\",\n  destinationOver: \"destination-over\",\n  destinationIn: \"destination-in\",\n  destinationOut: \"destination-out\",\n  destinationAtop: \"destination-atop\",\n  lighter: \"lighter\",\n  copy: \"copy\",\n  xor: \"xor\",\n  multiply: \"multiply\",\n  screen: \"screen\",\n  overlay: \"overlay\",\n  darken: \"darken\",\n  lighten: \"lighten\",\n  colorDodge: \"color-dodge\",\n  colorBurn: \"color-burn\",\n  hardLight: \"hard-light\",\n  softLight: \"soft-light\",\n  difference: \"difference\",\n  exclusion: \"exclusion\",\n  hue: \"hue\",\n  saturation: \"saturation\",\n  color: \"color\",\n  luminosity: \"luminosity\",\n};\n\nmodule.exports = {\n  MODE,\n};\n"
  },
  {
    "path": "constants/network.js",
    "content": "const NETWORK = {\n  eth: \"eth\",\n  sol: \"sol\",\n};\n\nmodule.exports = {\n  NETWORK,\n};\n"
  },
  {
    "path": "index.js",
    "content": "const basePath = process.cwd();\nconst { startCreating, buildSetup } = require(`${basePath}/src/main.js`);\n\n(() => {\n  buildSetup();\n  startCreating();\n})();\n"
  },
  {
    "path": "modules/HashlipsGiffer.js",
    "content": "const GifEncoder = require(\"gif-encoder-2\");\nconst { writeFile } = require(\"fs\");\n\nclass HashLipsGiffer {\n  constructor(_canvas, _ctx, _fileName, _repeat, _quality, _delay) {\n    this.canvas = _canvas;\n    this.ctx = _ctx;\n    this.fileName = _fileName;\n    this.repeat = _repeat;\n    this.quality = _quality;\n    this.delay = _delay;\n    this.initGifEncoder();\n  }\n\n  initGifEncoder = () => {\n    this.gifEncoder = new GifEncoder(this.canvas.width, this.canvas.height);\n    this.gifEncoder.setQuality(this.quality);\n    this.gifEncoder.setRepeat(this.repeat);\n    this.gifEncoder.setDelay(this.delay);\n  };\n\n  start = () => {\n    this.gifEncoder.start();\n  };\n\n  add = () => {\n    this.gifEncoder.addFrame(this.ctx);\n  };\n\n  stop = () => {\n    this.gifEncoder.finish();\n    const buffer = this.gifEncoder.out.getData();\n    writeFile(this.fileName, buffer, (error) => {});\n    console.log(`Created gif at ${this.fileName}`);\n  };\n}\n\nmodule.exports = HashLipsGiffer;\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"hashlips_art_engine\",\n  \"version\": \"1.1.1\",\n  \"description\": \"HashLips Art Engine is a tool used to create multiple different instances of artworks based on provided layers.\",\n  \"main\": \"index.js\",\n  \"bin\": \"index.js\",\n  \"pkg\": {\n    \"assets\": [\n      \"layers/**/*\",\n      \"node_modules/**/*\",\n      \"src/**/*\"\n    ]\n  },\n  \"scripts\": {\n    \"build\": \"node index.js\",\n    \"generate\": \"node index.js\",\n    \"rarity\": \"node utils/rarity.js\",\n    \"preview\": \"node utils/preview.js\",\n    \"pixelate\": \"node utils/pixelate.js\",\n    \"update_info\": \"node utils/update_info.js\",\n    \"preview_gif\": \"node utils/preview_gif.js\",\n    \"generate_metadata\": \"node utils/generate_metadata.js\"\n  },\n  \"author\": \"Daniel Eugene Botha (HashLips)\",\n  \"license\": \"MIT\",\n  \"dependencies\": {\n    \"canvas\": \"^2.8.0\",\n    \"gif-encoder-2\": \"^1.0.5\",\n    \"sha1\": \"^1.1.1\"\n  }\n}\n"
  },
  {
    "path": "src/config.js",
    "content": "const basePath = process.cwd();\nconst { MODE } = require(`${basePath}/constants/blend_mode.js`);\nconst { NETWORK } = require(`${basePath}/constants/network.js`);\n\nconst network = NETWORK.eth;\n\n// General metadata for Ethereum\nconst namePrefix = \"Your Collection\";\nconst description = \"Remember to replace this description\";\nconst baseUri = \"ipfs://NewUriToReplace\";\n\nconst solanaMetadata = {\n  symbol: \"YC\",\n  seller_fee_basis_points: 1000, // Define how much % you want from secondary market sales 1000 = 10%\n  external_url: \"https://www.youtube.com/c/hashlipsnft\",\n  creators: [\n    {\n      address: \"7fXNuer5sbZtaTEPhtJ5g5gNtuyRoKkvxdjEjEnPN4mC\",\n      share: 100,\n    },\n  ],\n};\n\n// If you have selected Solana then the collection starts from 0 automatically\nconst layerConfigurations = [\n  {\n    growEditionSizeTo: 5,\n    layersOrder: [\n      { name: \"Background\" },\n      { name: \"Eyeball\" },\n      { name: \"Eye color\" },\n      { name: \"Iris\" },\n      { name: \"Shine\" },\n      { name: \"Bottom lid\" },\n      { name: \"Top lid\" },\n    ],\n  },\n];\n\nconst shuffleLayerConfigurations = false;\n\nconst debugLogs = false;\n\nconst format = {\n  width: 512,\n  height: 512,\n  smoothing: false,\n};\n\nconst gif = {\n  export: false,\n  repeat: 0,\n  quality: 100,\n  delay: 500,\n};\n\nconst text = {\n  only: false,\n  color: \"#ffffff\",\n  size: 20,\n  xGap: 40,\n  yGap: 40,\n  align: \"left\",\n  baseline: \"top\",\n  weight: \"regular\",\n  family: \"Courier\",\n  spacer: \" => \",\n};\n\nconst pixelFormat = {\n  ratio: 2 / 128,\n};\n\nconst background = {\n  generate: true,\n  brightness: \"80%\",\n  static: false,\n  default: \"#000000\",\n};\n\nconst extraMetadata = {};\n\nconst rarityDelimiter = \"#\";\n\nconst uniqueDnaTorrance = 10000;\n\nconst preview = {\n  thumbPerRow: 5,\n  thumbWidth: 50,\n  imageRatio: format.height / format.width,\n  imageName: \"preview.png\",\n};\n\nconst preview_gif = {\n  numberOfImages: 5,\n  order: \"ASC\", // ASC, DESC, MIXED\n  repeat: 0,\n  quality: 100,\n  delay: 500,\n  imageName: \"preview.gif\",\n};\n\nmodule.exports = {\n  format,\n  baseUri,\n  description,\n  background,\n  uniqueDnaTorrance,\n  layerConfigurations,\n  rarityDelimiter,\n  preview,\n  shuffleLayerConfigurations,\n  debugLogs,\n  extraMetadata,\n  pixelFormat,\n  text,\n  namePrefix,\n  network,\n  solanaMetadata,\n  gif,\n  preview_gif,\n};\n"
  },
  {
    "path": "src/main.js",
    "content": "const basePath = process.cwd();\nconst { NETWORK } = require(`${basePath}/constants/network.js`);\nconst fs = require(\"fs\");\nconst sha1 = require(`${basePath}/node_modules/sha1`);\nconst { createCanvas, loadImage } = require(`${basePath}/node_modules/canvas`);\nconst buildDir = `${basePath}/build`;\nconst layersDir = `${basePath}/layers`;\nconst {\n  format,\n  baseUri,\n  description,\n  background,\n  uniqueDnaTorrance,\n  layerConfigurations,\n  rarityDelimiter,\n  shuffleLayerConfigurations,\n  debugLogs,\n  extraMetadata,\n  text,\n  namePrefix,\n  network,\n  solanaMetadata,\n  gif,\n} = require(`${basePath}/src/config.js`);\nconst canvas = createCanvas(format.width, format.height);\nconst ctx = canvas.getContext(\"2d\");\nctx.imageSmoothingEnabled = format.smoothing;\nvar metadataList = [];\nvar attributesList = [];\nvar dnaList = new Set();\nconst DNA_DELIMITER = \"-\";\nconst HashlipsGiffer = require(`${basePath}/modules/HashlipsGiffer.js`);\n\nlet hashlipsGiffer = null;\n\nconst buildSetup = () => {\n  if (fs.existsSync(buildDir)) {\n    fs.rmdirSync(buildDir, { recursive: true });\n  }\n  fs.mkdirSync(buildDir);\n  fs.mkdirSync(`${buildDir}/json`);\n  fs.mkdirSync(`${buildDir}/images`);\n  if (gif.export) {\n    fs.mkdirSync(`${buildDir}/gifs`);\n  }\n};\n\nconst getRarityWeight = (_str) => {\n  let nameWithoutExtension = _str.slice(0, -4);\n  var nameWithoutWeight = Number(\n    nameWithoutExtension.split(rarityDelimiter).pop()\n  );\n  if (isNaN(nameWithoutWeight)) {\n    nameWithoutWeight = 1;\n  }\n  return nameWithoutWeight;\n};\n\nconst cleanDna = (_str) => {\n  const withoutOptions = removeQueryStrings(_str);\n  var dna = Number(withoutOptions.split(\":\").shift());\n  return dna;\n};\n\nconst cleanName = (_str) => {\n  let nameWithoutExtension = _str.slice(0, -4);\n  var nameWithoutWeight = nameWithoutExtension.split(rarityDelimiter).shift();\n  return nameWithoutWeight;\n};\n\nconst getElements = (path) => {\n  return fs\n    .readdirSync(path)\n    .filter((item) => !/(^|\\/)\\.[^\\/\\.]/g.test(item))\n    .map((i, index) => {\n      if (i.includes(\"-\")) {\n        throw new Error(`layer name can not contain dashes, please fix: ${i}`);\n      }\n      return {\n        id: index,\n        name: cleanName(i),\n        filename: i,\n        path: `${path}${i}`,\n        weight: getRarityWeight(i),\n      };\n    });\n};\n\nconst layersSetup = (layersOrder) => {\n  const layers = layersOrder.map((layerObj, index) => ({\n    id: index,\n    elements: getElements(`${layersDir}/${layerObj.name}/`),\n    name:\n      layerObj.options?.[\"displayName\"] != undefined\n        ? layerObj.options?.[\"displayName\"]\n        : layerObj.name,\n    blend:\n      layerObj.options?.[\"blend\"] != undefined\n        ? layerObj.options?.[\"blend\"]\n        : \"source-over\",\n    opacity:\n      layerObj.options?.[\"opacity\"] != undefined\n        ? layerObj.options?.[\"opacity\"]\n        : 1,\n    bypassDNA:\n      layerObj.options?.[\"bypassDNA\"] !== undefined\n        ? layerObj.options?.[\"bypassDNA\"]\n        : false,\n  }));\n  return layers;\n};\n\nconst saveImage = (_editionCount) => {\n  fs.writeFileSync(\n    `${buildDir}/images/${_editionCount}.png`,\n    canvas.toBuffer(\"image/png\")\n  );\n};\n\nconst genColor = () => {\n  let hue = Math.floor(Math.random() * 360);\n  let pastel = `hsl(${hue}, 100%, ${background.brightness})`;\n  return pastel;\n};\n\nconst drawBackground = () => {\n  ctx.fillStyle = background.static ? background.default : genColor();\n  ctx.fillRect(0, 0, format.width, format.height);\n};\n\nconst addMetadata = (_dna, _edition) => {\n  let dateTime = Date.now();\n  let tempMetadata = {\n    name: `${namePrefix} #${_edition}`,\n    description: description,\n    image: `${baseUri}/${_edition}.png`,\n    dna: sha1(_dna),\n    edition: _edition,\n    date: dateTime,\n    ...extraMetadata,\n    attributes: attributesList,\n    compiler: \"HashLips Art Engine\",\n  };\n  if (network == NETWORK.sol) {\n    tempMetadata = {\n      //Added metadata for solana\n      name: tempMetadata.name,\n      symbol: solanaMetadata.symbol,\n      description: tempMetadata.description,\n      //Added metadata for solana\n      seller_fee_basis_points: solanaMetadata.seller_fee_basis_points,\n      image: `${_edition}.png`,\n      //Added metadata for solana\n      external_url: solanaMetadata.external_url,\n      edition: _edition,\n      ...extraMetadata,\n      attributes: tempMetadata.attributes,\n      properties: {\n        files: [\n          {\n            uri: `${_edition}.png`,\n            type: \"image/png\",\n          },\n        ],\n        category: \"image\",\n        creators: solanaMetadata.creators,\n      },\n    };\n  }\n  metadataList.push(tempMetadata);\n  attributesList = [];\n};\n\nconst addAttributes = (_element) => {\n  let selectedElement = _element.layer.selectedElement;\n  attributesList.push({\n    trait_type: _element.layer.name,\n    value: selectedElement.name,\n  });\n};\n\nconst loadLayerImg = async (_layer) => {\n  try {\n    return new Promise(async (resolve) => {\n      const image = await loadImage(`${_layer.selectedElement.path}`);\n      resolve({ layer: _layer, loadedImage: image });\n    });\n  } catch (error) {\n    console.error(\"Error loading image:\", error);\n  }\n};\n\nconst addText = (_sig, x, y, size) => {\n  ctx.fillStyle = text.color;\n  ctx.font = `${text.weight} ${size}pt ${text.family}`;\n  ctx.textBaseline = text.baseline;\n  ctx.textAlign = text.align;\n  ctx.fillText(_sig, x, y);\n};\n\nconst drawElement = (_renderObject, _index, _layersLen) => {\n  ctx.globalAlpha = _renderObject.layer.opacity;\n  ctx.globalCompositeOperation = _renderObject.layer.blend;\n  text.only\n    ? addText(\n        `${_renderObject.layer.name}${text.spacer}${_renderObject.layer.selectedElement.name}`,\n        text.xGap,\n        text.yGap * (_index + 1),\n        text.size\n      )\n    : ctx.drawImage(\n        _renderObject.loadedImage,\n        0,\n        0,\n        format.width,\n        format.height\n      );\n\n  addAttributes(_renderObject);\n};\n\nconst constructLayerToDna = (_dna = \"\", _layers = []) => {\n  let mappedDnaToLayers = _layers.map((layer, index) => {\n    let selectedElement = layer.elements.find(\n      (e) => e.id == cleanDna(_dna.split(DNA_DELIMITER)[index])\n    );\n    return {\n      name: layer.name,\n      blend: layer.blend,\n      opacity: layer.opacity,\n      selectedElement: selectedElement,\n    };\n  });\n  return mappedDnaToLayers;\n};\n\n/**\n * In some cases a DNA string may contain optional query parameters for options\n * such as bypassing the DNA isUnique check, this function filters out those\n * items without modifying the stored DNA.\n *\n * @param {String} _dna New DNA string\n * @returns new DNA string with any items that should be filtered, removed.\n */\nconst filterDNAOptions = (_dna) => {\n  const dnaItems = _dna.split(DNA_DELIMITER);\n  const filteredDNA = dnaItems.filter((element) => {\n    const query = /(\\?.*$)/;\n    const querystring = query.exec(element);\n    if (!querystring) {\n      return true;\n    }\n    const options = querystring[1].split(\"&\").reduce((r, setting) => {\n      const keyPairs = setting.split(\"=\");\n      return { ...r, [keyPairs[0]]: keyPairs[1] };\n    }, []);\n\n    return options.bypassDNA;\n  });\n\n  return filteredDNA.join(DNA_DELIMITER);\n};\n\n/**\n * Cleaning function for DNA strings. When DNA strings include an option, it\n * is added to the filename with a ?setting=value query string. It needs to be\n * removed to properly access the file name before Drawing.\n *\n * @param {String} _dna The entire newDNA string\n * @returns Cleaned DNA string without querystring parameters.\n */\nconst removeQueryStrings = (_dna) => {\n  const query = /(\\?.*$)/;\n  return _dna.replace(query, \"\");\n};\n\nconst isDnaUnique = (_DnaList = new Set(), _dna = \"\") => {\n  const _filteredDNA = filterDNAOptions(_dna);\n  return !_DnaList.has(_filteredDNA);\n};\n\nconst createDna = (_layers) => {\n  let randNum = [];\n  _layers.forEach((layer) => {\n    var totalWeight = 0;\n    layer.elements.forEach((element) => {\n      totalWeight += element.weight;\n    });\n    // number between 0 - totalWeight\n    let random = Math.floor(Math.random() * totalWeight);\n    for (var i = 0; i < layer.elements.length; i++) {\n      // subtract the current weight from the random weight until we reach a sub zero value.\n      random -= layer.elements[i].weight;\n      if (random < 0) {\n        return randNum.push(\n          `${layer.elements[i].id}:${layer.elements[i].filename}${\n            layer.bypassDNA ? \"?bypassDNA=true\" : \"\"\n          }`\n        );\n      }\n    }\n  });\n  return randNum.join(DNA_DELIMITER);\n};\n\nconst writeMetaData = (_data) => {\n  fs.writeFileSync(`${buildDir}/json/_metadata.json`, _data);\n};\n\nconst saveMetaDataSingleFile = (_editionCount) => {\n  let metadata = metadataList.find((meta) => meta.edition == _editionCount);\n  debugLogs\n    ? console.log(\n        `Writing metadata for ${_editionCount}: ${JSON.stringify(metadata)}`\n      )\n    : null;\n  fs.writeFileSync(\n    `${buildDir}/json/${_editionCount}.json`,\n    JSON.stringify(metadata, null, 2)\n  );\n};\n\nfunction shuffle(array) {\n  let currentIndex = array.length,\n    randomIndex;\n  while (currentIndex != 0) {\n    randomIndex = Math.floor(Math.random() * currentIndex);\n    currentIndex--;\n    [array[currentIndex], array[randomIndex]] = [\n      array[randomIndex],\n      array[currentIndex],\n    ];\n  }\n  return array;\n}\n\nconst startCreating = async () => {\n  let layerConfigIndex = 0;\n  let editionCount = 1;\n  let failedCount = 0;\n  let abstractedIndexes = [];\n  for (\n    let i = network == NETWORK.sol ? 0 : 1;\n    i <= layerConfigurations[layerConfigurations.length - 1].growEditionSizeTo;\n    i++\n  ) {\n    abstractedIndexes.push(i);\n  }\n  if (shuffleLayerConfigurations) {\n    abstractedIndexes = shuffle(abstractedIndexes);\n  }\n  debugLogs\n    ? console.log(\"Editions left to create: \", abstractedIndexes)\n    : null;\n  while (layerConfigIndex < layerConfigurations.length) {\n    const layers = layersSetup(\n      layerConfigurations[layerConfigIndex].layersOrder\n    );\n    while (\n      editionCount <= layerConfigurations[layerConfigIndex].growEditionSizeTo\n    ) {\n      let newDna = createDna(layers);\n      if (isDnaUnique(dnaList, newDna)) {\n        let results = constructLayerToDna(newDna, layers);\n        let loadedElements = [];\n\n        results.forEach((layer) => {\n          loadedElements.push(loadLayerImg(layer));\n        });\n\n        await Promise.all(loadedElements).then((renderObjectArray) => {\n          debugLogs ? console.log(\"Clearing canvas\") : null;\n          ctx.clearRect(0, 0, format.width, format.height);\n          if (gif.export) {\n            hashlipsGiffer = new HashlipsGiffer(\n              canvas,\n              ctx,\n              `${buildDir}/gifs/${abstractedIndexes[0]}.gif`,\n              gif.repeat,\n              gif.quality,\n              gif.delay\n            );\n            hashlipsGiffer.start();\n          }\n          if (background.generate) {\n            drawBackground();\n          }\n          renderObjectArray.forEach((renderObject, index) => {\n            drawElement(\n              renderObject,\n              index,\n              layerConfigurations[layerConfigIndex].layersOrder.length\n            );\n            if (gif.export) {\n              hashlipsGiffer.add();\n            }\n          });\n          if (gif.export) {\n            hashlipsGiffer.stop();\n          }\n          debugLogs\n            ? console.log(\"Editions left to create: \", abstractedIndexes)\n            : null;\n          saveImage(abstractedIndexes[0]);\n          addMetadata(newDna, abstractedIndexes[0]);\n          saveMetaDataSingleFile(abstractedIndexes[0]);\n          console.log(\n            `Created edition: ${abstractedIndexes[0]}, with DNA: ${sha1(\n              newDna\n            )}`\n          );\n        });\n        dnaList.add(filterDNAOptions(newDna));\n        editionCount++;\n        abstractedIndexes.shift();\n      } else {\n        console.log(\"DNA exists!\");\n        failedCount++;\n        if (failedCount >= uniqueDnaTorrance) {\n          console.log(\n            `You need more layers or elements to grow your edition to ${layerConfigurations[layerConfigIndex].growEditionSizeTo} artworks!`\n          );\n          process.exit();\n        }\n      }\n    }\n    layerConfigIndex++;\n  }\n  writeMetaData(JSON.stringify(metadataList, null, 2));\n};\n\nmodule.exports = { startCreating, buildSetup, getElements };\n"
  },
  {
    "path": "utils/generate_metadata.js",
    "content": "const fs = require(\"fs\");\nconst path = require(\"path\");\nconst { createCanvas, loadImage } = require(\"canvas\");\nconst basePath = process.cwd();\nconst buildDir = `${basePath}/build/json`;\nconst inputDir = `${basePath}/build/images`;\nconst {\n  format,\n  namePrefix,\n  description,\n  baseUri,\n} = require(`${basePath}/src/config.js`);\nconst console = require(\"console\");\nconst canvas = createCanvas(format.width, format.height);\nconst ctx = canvas.getContext(\"2d\");\nconst metadataList = [];\n\nconst buildSetup = () => {\n  if (fs.existsSync(buildDir)) {\n    fs.rmdirSync(buildDir, { recursive: true });\n  }\n  fs.mkdirSync(buildDir);\n};\n\nconst getImages = (_dir) => {\n  try {\n    return fs\n      .readdirSync(_dir)\n      .filter((item) => {\n        let extension = path.extname(`${_dir}${item}`);\n        if (extension == \".png\" || extension == \".jpg\") {\n          return item;\n        }\n      })\n      .map((i) => {\n        return {\n          filename: i,\n          path: `${_dir}/${i}`,\n        };\n      });\n  } catch {\n    return null;\n  }\n};\n\nconst loadImgData = async (_imgObject) => {\n  try {\n    const image = await loadImage(`${_imgObject.path}`);\n    return {\n      imgObject: _imgObject,\n      loadedImage: image,\n    };\n  } catch (error) {\n    console.error(\"Error loading image:\", error);\n  }\n};\n\nconst draw = (_imgObject) => {\n  let w = canvas.width;\n  let h = canvas.height;\n  ctx.drawImage(_imgObject.loadedImage, 0, 0, w, h);\n};\n\nconst addRarity = () => {\n  let w = canvas.width;\n  let h = canvas.height;\n  let i = -4;\n  let count = 0;\n  let imgdata = ctx.getImageData(0, 0, w, h);\n  let rgb = imgdata.data;\n  let newRgb = { r: 0, g: 0, b: 0 };\n  const tolerance = 15;\n  const rareColorBase = \"NOT a Hot Dog\";\n  const rareColor = [\n    { name: \"Hot Dog\", rgb: { r: 192, g: 158, b: 131 } },\n    { name: \"Hot Dog\", rgb: { r: 128, g: 134, b: 90 } },\n    { name: \"Hot Dog\", rgb: { r: 113, g: 65, b: 179 } },\n    { name: \"Hot Dog\", rgb: { r: 162, g: 108, b: 67 } },\n  ];\n\n  while ((i += 10 * 4) < rgb.length) {\n    ++count;\n    newRgb.r += rgb[i];\n    newRgb.g += rgb[i + 1];\n    newRgb.b += rgb[i + 2];\n  }\n\n  newRgb.r = ~~(newRgb.r / count);\n  newRgb.g = ~~(newRgb.g / count);\n  newRgb.b = ~~(newRgb.b / count);\n\n  let rarity = rareColorBase;\n\n  rareColor.forEach((color) => {\n    if (isNeighborColor(newRgb, color.rgb, tolerance)) {\n      rarity = color.name;\n    }\n  });\n\n  console.log(newRgb);\n  console.log(rarity);\n\n  return [\n    {\n      trait_type: \"average color\",\n      value: `rgb(${newRgb.r},${newRgb.g},${newRgb.b})`,\n    },\n    {\n      trait_type: \"What is this?\",\n      value: rarity,\n    },\n    {\n      trait_type: \"date\",\n      value: randomIntFromInterval(1500, 1900),\n    },\n  ];\n};\n\nrandomIntFromInterval = (min, max) => {\n  return Math.floor(Math.random() * (max - min + 1) + min);\n};\n\nisNeighborColor = (color1, color2, tolerance) => {\n  return (\n    Math.abs(color1.r - color2.r) <= tolerance &&\n    Math.abs(color1.g - color2.g) <= tolerance &&\n    Math.abs(color1.b - color2.b) <= tolerance\n  );\n};\n\nconst saveMetadata = (_loadedImageObject) => {\n  let shortName = _loadedImageObject.imgObject.filename.replace(\n    /\\.[^/.]+$/,\n    \"\"\n  );\n\n  let tempAttributes = [];\n  tempAttributes.push(addRarity());\n\n  let tempMetadata = {\n    name: `${namePrefix} #${shortName}`,\n    description: description,\n    image: `${baseUri}/${shortName}.png`,\n    edition: Number(shortName),\n    attributes: tempAttributes,\n    compiler: \"HashLips Art Engine\",\n  };\n  fs.writeFileSync(\n    `${buildDir}/${shortName}.json`,\n    JSON.stringify(tempMetadata, null, 2)\n  );\n  metadataList.push(tempMetadata);\n};\n\nconst writeMetaData = (_data) => {\n  fs.writeFileSync(`${buildDir}/_metadata.json`, _data);\n};\n\nconst startCreating = async () => {\n  const images = getImages(inputDir);\n  if (images == null) {\n    console.log(\"Please generate collection first.\");\n    return;\n  }\n  let loadedImageObjects = [];\n  images.forEach((imgObject) => {\n    loadedImageObjects.push(loadImgData(imgObject));\n  });\n  await Promise.all(loadedImageObjects).then((loadedImageObjectArray) => {\n    loadedImageObjectArray.forEach((loadedImageObject) => {\n      draw(loadedImageObject);\n      saveMetadata(loadedImageObject);\n      console.log(\n        `Created metadata for image: ${loadedImageObject.imgObject.filename}`\n      );\n    });\n  });\n  writeMetaData(JSON.stringify(metadataList, null, 2));\n};\n\nbuildSetup();\nstartCreating();\n"
  },
  {
    "path": "utils/pixelate.js",
    "content": "const fs = require(\"fs\");\nconst path = require(\"path\");\nconst { createCanvas, loadImage } = require(\"canvas\");\nconst basePath = process.cwd();\nconst buildDir = `${basePath}/build/pixel_images`;\nconst inputDir = `${basePath}/build/images`;\nconst { format, pixelFormat } = require(`${basePath}/src/config.js`);\nconst console = require(\"console\");\nconst canvas = createCanvas(format.width, format.height);\nconst ctx = canvas.getContext(\"2d\");\n\nconst buildSetup = () => {\n  if (fs.existsSync(buildDir)) {\n    fs.rmdirSync(buildDir, { recursive: true });\n  }\n  fs.mkdirSync(buildDir);\n};\n\nconst getImages = (_dir) => {\n  try {\n    return fs\n      .readdirSync(_dir)\n      .filter((item) => {\n        let extension = path.extname(`${_dir}${item}`);\n        if (extension == \".png\" || extension == \".jpg\") {\n          return item;\n        }\n      })\n      .map((i) => {\n        return {\n          filename: i,\n          path: `${_dir}/${i}`,\n        };\n      });\n  } catch {\n    return null;\n  }\n};\n\nconst loadImgData = async (_imgObject) => {\n  try {\n    const image = await loadImage(`${_imgObject.path}`);\n    return {\n      imgObject: _imgObject,\n      loadedImage: image,\n    };\n  } catch (error) {\n    console.error(\"Error loading image:\", error);\n  }\n};\n\nconst draw = (_imgObject) => {\n  let size = pixelFormat.ratio;\n  let w = canvas.width * size;\n  let h = canvas.height * size;\n  ctx.imageSmoothingEnabled = false;\n  ctx.drawImage(_imgObject.loadedImage, 0, 0, w, h);\n  ctx.drawImage(canvas, 0, 0, w, h, 0, 0, canvas.width, canvas.height);\n};\n\nconst saveImage = (_loadedImageObject) => {\n  fs.writeFileSync(\n    `${buildDir}/${_loadedImageObject.imgObject.filename}`,\n    canvas.toBuffer(\"image/png\")\n  );\n};\n\nconst startCreating = async () => {\n  const images = getImages(inputDir);\n  if (images == null) {\n    console.log(\"Please generate collection first.\");\n    return;\n  }\n  let loadedImageObjects = [];\n  images.forEach((imgObject) => {\n    loadedImageObjects.push(loadImgData(imgObject));\n  });\n  await Promise.all(loadedImageObjects).then((loadedImageObjectArray) => {\n    loadedImageObjectArray.forEach((loadedImageObject) => {\n      draw(loadedImageObject);\n      saveImage(loadedImageObject);\n      console.log(`Pixelated image: ${loadedImageObject.imgObject.filename}`);\n    });\n  });\n};\n\nbuildSetup();\nstartCreating();\n"
  },
  {
    "path": "utils/preview.js",
    "content": "const basePath = process.cwd();\nconst fs = require(\"fs\");\nconst { createCanvas, loadImage } = require(\"canvas\");\nconst buildDir = `${basePath}/build`;\n\nconst { preview } = require(`${basePath}/src/config.js`);\n\n// read json data\nconst rawdata = fs.readFileSync(`${basePath}/build/json/_metadata.json`);\nconst metadataList = JSON.parse(rawdata);\n\nconst saveProjectPreviewImage = async (_data) => {\n  // Extract from preview config\n  const { thumbWidth, thumbPerRow, imageRatio, imageName } = preview;\n  // Calculate height on the fly\n  const thumbHeight = thumbWidth * imageRatio;\n  // Prepare canvas\n  const previewCanvasWidth = thumbWidth * thumbPerRow;\n  const previewCanvasHeight =\n    thumbHeight * Math.ceil(_data.length / thumbPerRow);\n  // Shout from the mountain tops\n  console.log(\n    `Preparing a ${previewCanvasWidth}x${previewCanvasHeight} project preview with ${_data.length} thumbnails.`\n  );\n\n  // Initiate the canvas now that we have calculated everything\n  const previewPath = `${buildDir}/${imageName}`;\n  const previewCanvas = createCanvas(previewCanvasWidth, previewCanvasHeight);\n  const previewCtx = previewCanvas.getContext(\"2d\");\n\n  // Iterate all NFTs and insert thumbnail into preview image\n  // Don't want to rely on \"edition\" for assuming index\n  for (let index = 0; index < _data.length; index++) {\n    const nft = _data[index];\n    await loadImage(`${buildDir}/images/${nft.edition}.png`).then((image) => {\n      previewCtx.drawImage(\n        image,\n        thumbWidth * (index % thumbPerRow),\n        thumbHeight * Math.trunc(index / thumbPerRow),\n        thumbWidth,\n        thumbHeight\n      );\n    });\n  }\n\n  // Write Project Preview to file\n  fs.writeFileSync(previewPath, previewCanvas.toBuffer(\"image/png\"));\n  console.log(`Project preview image located at: ${previewPath}`);\n};\n\nsaveProjectPreviewImage(metadataList);\n"
  },
  {
    "path": "utils/preview_gif.js",
    "content": "const basePath = process.cwd();\nconst fs = require(\"fs\");\nconst { createCanvas, loadImage } = require(\"canvas\");\nconst buildDir = `${basePath}/build`;\nconst imageDir = `${buildDir}/images`;\nconst { format, preview_gif } = require(`${basePath}/src/config.js`);\nconst canvas = createCanvas(format.width, format.height);\nconst ctx = canvas.getContext(\"2d\");\n\nconst HashlipsGiffer = require(`${basePath}/modules/HashlipsGiffer.js`);\nlet hashlipsGiffer = null;\n\nconst loadImg = async (_img) => {\n  return new Promise(async (resolve) => {\n    const loadedImage = await loadImage(`${_img}`);\n    resolve({ loadedImage: loadedImage });\n  });\n};\n\n// read image paths\nconst imageList = [];\nconst rawdata = fs.readdirSync(imageDir).forEach((file) => {\n  imageList.push(loadImg(`${imageDir}/${file}`));\n});\n\nconst saveProjectPreviewGIF = async (_data) => {\n  // Extract from preview config\n  const { numberOfImages, order, repeat, quality, delay, imageName } =\n    preview_gif;\n  // Extract from format config\n  const { width, height } = format;\n  // Prepare canvas\n  const previewCanvasWidth = width;\n  const previewCanvasHeight = height;\n\n  if (_data.length < numberOfImages) {\n    console.log(\n      `You do not have enough images to create a gif with ${numberOfImages} images.`\n    );\n  } else {\n    // Shout from the mountain tops\n    console.log(\n      `Preparing a ${previewCanvasWidth}x${previewCanvasHeight} project preview with ${_data.length} images.`\n    );\n    const previewPath = `${buildDir}/${imageName}`;\n\n    ctx.clearRect(0, 0, width, height);\n\n    hashlipsGiffer = new HashlipsGiffer(\n      canvas,\n      ctx,\n      `${previewPath}`,\n      repeat,\n      quality,\n      delay\n    );\n    hashlipsGiffer.start();\n\n    await Promise.all(_data).then((renderObjectArray) => {\n      // Determin the order of the Images before creating the gif\n      if (order == \"ASC\") {\n        // Do nothing\n      } else if (order == \"DESC\") {\n        renderObjectArray.reverse();\n      } else if (order == \"MIXED\") {\n        renderObjectArray = renderObjectArray.sort(() => Math.random() - 0.5);\n      }\n\n      // Reduce the size of the array of Images to the desired amount\n      if (parseInt(numberOfImages) > 0) {\n        renderObjectArray = renderObjectArray.slice(0, numberOfImages);\n      }\n\n      renderObjectArray.forEach((renderObject, index) => {\n        ctx.globalAlpha = 1;\n        ctx.globalCompositeOperation = \"source-over\";\n        ctx.drawImage(\n          renderObject.loadedImage,\n          0,\n          0,\n          previewCanvasWidth,\n          previewCanvasHeight\n        );\n        hashlipsGiffer.add();\n      });\n    });\n    hashlipsGiffer.stop();\n  }\n};\n\nsaveProjectPreviewGIF(imageList);\n"
  },
  {
    "path": "utils/rarity.js",
    "content": "const basePath = process.cwd();\nconst fs = require(\"fs\");\nconst layersDir = `${basePath}/layers`;\n\nconst { layerConfigurations } = require(`${basePath}/src/config.js`);\n\nconst { getElements } = require(\"../src/main.js\");\n\n// read json data\nlet rawdata = fs.readFileSync(`${basePath}/build/json/_metadata.json`);\nlet data = JSON.parse(rawdata);\nlet editionSize = data.length;\n\nlet rarityData = [];\n\n// intialize layers to chart\nlayerConfigurations.forEach((config) => {\n  let layers = config.layersOrder;\n\n  layers.forEach((layer) => {\n    // get elements for each layer\n    let elementsForLayer = [];\n    let elements = getElements(`${layersDir}/${layer.name}/`);\n    elements.forEach((element) => {\n      // just get name and weight for each element\n      let rarityDataElement = {\n        trait: element.name,\n        weight: element.weight.toFixed(0),\n        occurrence: 0, // initialize at 0\n      };\n      elementsForLayer.push(rarityDataElement);\n    });\n    let layerName =\n      layer.options?.[\"displayName\"] != undefined\n        ? layer.options?.[\"displayName\"]\n        : layer.name;\n    // don't include duplicate layers\n    if (!rarityData.includes(layer.name)) {\n      // add elements for each layer to chart\n      rarityData[layerName] = elementsForLayer;\n    }\n  });\n});\n\n// fill up rarity chart with occurrences from metadata\ndata.forEach((element) => {\n  let attributes = element.attributes;\n  attributes.forEach((attribute) => {\n    let traitType = attribute.trait_type;\n    let value = attribute.value;\n\n    let rarityDataTraits = rarityData[traitType];\n    rarityDataTraits.forEach((rarityDataTrait) => {\n      if (rarityDataTrait.trait == value) {\n        // keep track of occurrences\n        rarityDataTrait.occurrence++;\n      }\n    });\n  });\n});\n\n// convert occurrences to occurence string\nfor (var layer in rarityData) {\n  for (var attribute in rarityData[layer]) {\n    // get chance\n    let chance =\n      ((rarityData[layer][attribute].occurrence / editionSize) * 100).toFixed(2);\n\n    // show two decimal places in percent\n    rarityData[layer][attribute].occurrence =\n      `${rarityData[layer][attribute].occurrence} in ${editionSize} editions (${chance} %)`;\n  }\n}\n\n// print out rarity data\nfor (var layer in rarityData) {\n  console.log(`Trait type: ${layer}`);\n  for (var trait in rarityData[layer]) {\n    console.log(rarityData[layer][trait]);\n  }\n  console.log();\n}\n"
  },
  {
    "path": "utils/update_info.js",
    "content": "const basePath = process.cwd();\nconst { NETWORK } = require(`${basePath}/constants/network.js`);\nconst fs = require(\"fs\");\n\nconst {\n  baseUri,\n  description,\n  namePrefix,\n  network,\n  solanaMetadata,\n} = require(`${basePath}/src/config.js`);\n\n// read json data\nlet rawdata = fs.readFileSync(`${basePath}/build/json/_metadata.json`);\nlet data = JSON.parse(rawdata);\n\ndata.forEach((item) => {\n  if (network == NETWORK.sol) {\n    item.name = `${namePrefix} #${item.edition}`;\n    item.description = description;\n    item.creators = solanaMetadata.creators;\n  } else {\n    item.name = `${namePrefix} #${item.edition}`;\n    item.description = description;\n    item.image = `${baseUri}/${item.edition}.png`;\n  }\n  fs.writeFileSync(\n    `${basePath}/build/json/${item.edition}.json`,\n    JSON.stringify(item, null, 2)\n  );\n});\n\nfs.writeFileSync(\n  `${basePath}/build/json/_metadata.json`,\n  JSON.stringify(data, null, 2)\n);\n\nif (network == NETWORK.sol) {\n  console.log(`Updated description for images to ===> ${description}`);\n  console.log(`Updated name prefix for images to ===> ${namePrefix}`);\n  console.log(\n    `Updated creators for images to ===> ${JSON.stringify(\n      solanaMetadata.creators\n    )}`\n  );\n} else {\n  console.log(`Updated baseUri for images to ===> ${baseUri}`);\n  console.log(`Updated description for images to ===> ${description}`);\n  console.log(`Updated name prefix for images to ===> ${namePrefix}`);\n}\n"
  }
]