HashLips / generative-art-opensource

Create generative art by using the canvas api and node js, feel free to contribute to this repo with new ideas.
MIT License
1.36k stars 695 forks source link

Help Combining Two Branches #77

Open Smileez1234 opened 2 years ago

Smileez1234 commented 2 years ago

I had my rarities sorted out perfectly in branch one but now Id like to use the advanced Meta Data output from branch 3. The rarities in branch 3 just don't seem to work correctly no matter how I adjust the weights. This is higher than my skill level but I tried to copy the rarity code from branch 1 to 3 but I broke it. This is why I cant have nice things. I know this is alot but Id appreciate any suggestions.

This is my Config file:

const fs = require("fs"); const width = 1000; const height = 1000; const dir = __dirname; const description = "blah blah."; const baseImageUri = "https://hashlips/nft"; const startEditionFrom = 1; const endEditionAt = 10; const editionSize = 10; const raceWeights = [ { value: "Blah", from: 1, to: editionSize, }, ];

// create required weights // for each weight, call 'addRarity' with the id and from which to which element this rarity should be applied let rarityWeights = [ addRarity('zen', 1, 600), addRarity('rare', 600, 3900), addRarity('common', 3900, 10000) ];

// create required layers // for each layer, call 'addLayer' with the id and optionally the positioning and size // the id would be the name of the folder in your input directory, e.g. 'ball' for ./input/ball const layers = [ addLayer('background', { x: 0, y: 0 }, { width: width, height: height }), addLayer('face'), addLayer('eyes'), addLayer('mouth'), addLayer('nose'), addLayer('hat') ];

// provide any specific percentages that are required for a given layer and rarity level // all provided options are used based on their percentage values to decide which layer to select from addRarityPercentForLayer('zen', 'background', { 'zen': 25, 'rare': 37, 'common': 38 }); addRarityPercentForLayer('rare', 'background', { 'zen': 8, 'rare': 42, 'common': 50 }); addRarityPercentForLayer('common', 'background', { 'zen': 2, 'rare': 24, 'common': 74 }); addRarityPercentForLayer('zen', 'face', { 'zen': 25, 'rare': 37, 'common': 38 }); addRarityPercentForLayer('rare', 'face', { 'zen': 8, 'rare': 42, 'common': 50 }); addRarityPercentForLayer('common', 'face', { 'zen': 2, 'rare': 24, 'common': 74 }); addRarityPercentForLayer('zen', 'eyes', { 'zen': 25, 'rare': 37, 'common': 38 }); addRarityPercentForLayer('rare', 'eyes', { 'zen': 8, 'rare': 42, 'common': 50 }); addRarityPercentForLayer('common', 'eyes', { 'zen': 2, 'rare': 24, 'common': 74 }); addRarityPercentForLayer('zen', 'hat', { 'zen': 25, 'rare': 37, 'common': 38 }); addRarityPercentForLayer('rare', 'hat', { 'zen': 8, 'rare': 42, 'common': 50 }); addRarityPercentForLayer('common', 'hat', { 'zen': 2, 'rare': 24, 'common': 74 }); addRarityPercentForLayer('zen', 'mouth', { 'zen': 25, 'rare': 37, 'common': 38 }); addRarityPercentForLayer('rare', 'mouth', { 'zen': 8, 'rare': 42, 'common': 50 }); addRarityPercentForLayer('common', 'mouth', { 'zen': 2, 'rare': 24, 'common': 74 }); addRarityPercentForLayer('zen', 'nose', { 'zen': 25, 'rare': 37, 'common': 38 }); addRarityPercentForLayer('rare', 'nose', { 'zen': 8, 'rare': 42, 'common': 50 }); addRarityPercentForLayer('common', 'nose', { 'zen': 2, 'rare': 24, 'common': 74 });

module.exports = { width, height, description, baseImageUri, editionSize, startEditionFrom, endEditionAt, races, raceWeights, };

Andy my index.js:

const fs = require("fs"); const { createCanvas, loadImage } = require("canvas"); const { width, height, description, baseImageUri, editionSize, startEditionFrom, endEditionAt, races, raceWeights, } = require("./input/config.js"); const console = require("console"); const canvas = createCanvas(width, height); const ctx = canvas.getContext("2d"); var metadataList = []; var attributesList = []; var dnaList = [];

const saveImage = (_editionCount) => { fs.writeFileSync( ./output/${_editionCount}.png, canvas.toBuffer("image/png") ); };

const signImage = (_sig) => { ctx.fillStyle = "#ffffff"; ctx.font = "bold 30pt Verdana"; ctx.textBaseline = "top"; ctx.textAlign = "left"; ctx.fillText(_sig, 40, 40); };

const genColor = () => { let hue = Math.floor(Math.random() * 360); let pastel = hsl(${hue}, 100%, 85%); return pastel; };

const drawBackground = () => { ctx.fillStyle = genColor(); ctx.fillRect(0, 0, width, height); };

const addMetadata = (_dna, _edition) => { let dateTime = Date.now(); let tempMetadata = { dna: _dna.join(""), name: #${_edition}, description: description, image: ${baseImageUri}/${_edition}.png, edition: _edition, date: dateTime, attributes: attributesList, }; metadataList.push(tempMetadata); attributesList = []; };

const addAttributes = (_element) => { let selectedElement = _element.layer.selectedElement; attributesList.push({ trait_type: _element.layer.name, value: selectedElement.name, }); };

const loadLayerImg = async (_layer) => { return new Promise(async (resolve) => { const image = await loadImage(${_layer.selectedElement.path}); resolve({ layer: _layer, loadedImage: image }); }); };

const drawElement = (_element) => { ctx.drawImage( _element.loadedImage, _element.layer.position.x, _element.layer.position.y, _element.layer.size.width, _element.layer.size.height ); addAttributes(_element); };

const constructLayerToDna = (_dna = [], _races = [], _race) => { let mappedDnaToLayers = _races[_race].layers.map((layer, index) => { let selectedElement = layer.elements.find((e) => e.id == _dna[index]); return { name: layer.name, position: layer.position, size: layer.size, selectedElement: selectedElement, }; });

return mappedDnaToLayers; };

const getRace = (_editionCount) => { let race = "No Race"; raceWeights.forEach((raceWeight) => { if (_editionCount >= raceWeight.from && _editionCount <= raceWeight.to) { race = raceWeight.value; } }); return race; };

const isDnaUnique = (_DnaList = [], _dna = []) => { let foundDna = _DnaList.find((i) => i.join("") === _dna.join("")); return foundDna == undefined ? true : false; };

const createDna = (_races, _race) => { let randNum = []; _races[_race].layers.forEach((layer) => { let randElementNum = Math.floor(Math.random() * 100); let num = 0; layer.elements.forEach((element) => { if (randElementNum >= 100 - element.weight) { num = element.id; } }); randNum.push(num); }); return randNum; };

const writeMetaData = (_data) => { fs.writeFileSync("./output/_metadata.json", _data); };

const saveMetaDataSingleFile = (_editionCount) => { fs.writeFileSync( ./output/${_editionCount}.json, JSON.stringify(metadataList.find((meta) => meta.edition == _editionCount)) ); };

const startCreating = async () => { writeMetaData(""); let editionCount = startEditionFrom; while (editionCount <= endEditionAt) { let race = getRace(editionCount); let newDna = createDna(races, race);

if (isDnaUnique(dnaList, newDna)) {
  let results = constructLayerToDna(newDna, races, race);
  let loadedElements = []; //promise array
  results.forEach((layer) => {
    loadedElements.push(loadLayerImg(layer));
  });

  await Promise.all(loadedElements).then((elementArray) => {
    ctx.clearRect(0, 0, width, height);
    // drawBackground();
    elementArray.forEach((element) => {
      drawElement(element);
    });
    signImage(`#${editionCount}`);
    saveImage(editionCount);
    addMetadata(newDna, editionCount);
    saveMetaDataSingleFile(editionCount);
    console.log(
      `Created edition: ${editionCount}, Race: ${race} with DNA: ${newDna}`
    );
  });
  dnaList.push(newDna);
  editionCount++;
} else {
  console.log("DNA exists!");
}

} writeMetaData(JSON.stringify(metadataList)); };

startCreating();

Im getting the following error:

ReferenceError: addRarity is not defined at Object. (E:\GLYPH\Hash Lips Code\generative-art-opensource-3 - Copy\input\config.js:20:21) at Module._compile (internal/modules/cjs/loader.js:1072:14) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10) at Module.load (internal/modules/cjs/loader.js:937:32) at Function.Module._load (internal/modules/cjs/loader.js:778:12) at Module.require (internal/modules/cjs/loader.js:961:19) at require (internal/modules/cjs/helpers.js:92:18) at Object. (E:\GLYPH\Hash Lips Code\generative-art-opensource-3 - Copy\index.js:13:5) at Module._compile (internal/modules/cjs/loader.js:1072:14) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)

jayvi commented 2 years ago

everyone have issues with layers and rarity mate lets hope we get help soon