Skip to content

Commit

Permalink
Merge pull request #159 from HashLips/dev
Browse files Browse the repository at this point in the history
Merge
  • Loading branch information
HashLips authored Oct 27, 2021
2 parents 8890c4d + 14cadd5 commit 3212078
Show file tree
Hide file tree
Showing 5 changed files with 164 additions and 7 deletions.
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ If you want to play around with different blending modes, you can add a `blend:

If 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.

If 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.

To 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.

Here is an example on how you can play around with both filter fields:
Expand All @@ -120,7 +122,11 @@ const layerConfigurations = [
{
growEditionSizeTo: 5,
layersOrder: [
{ name: "Background" },
{ name: "Background" , {
options: {
bypassDNA: false;
}
}},
{ name: "Eyeball" },
{
name: "Eye color",
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"rarity": "node utils/rarity.js",
"preview": "node utils/preview.js",
"pixelate": "node utils/pixelate.js",
"update_info": "node utils/update_info.js"
"update_info": "node utils/update_info.js",
"preview_gif": "node utils/preview_gif.js"
},
"author": "Daniel Eugene Botha (HashLips)",
"license": "MIT",
Expand Down
12 changes: 11 additions & 1 deletion src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,19 @@ const uniqueDnaTorrance = 10000;
const preview = {
thumbPerRow: 5,
thumbWidth: 50,
imageRatio: format.width / format.height,
imageRatio: format.height / format.width,
imageName: "preview.png",
};

const preview_gif = {
numberOfImages: 5,
order: "ASC", // ASC, DESC, MIXED
repeat: 0,
quality: 100,
delay: 500,
imageName: "preview.gif",
};

module.exports = {
format,
baseUri,
Expand All @@ -112,4 +121,5 @@ module.exports = {
network,
solanaMetadata,
gif,
preview_gif,
};
54 changes: 50 additions & 4 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ const getRarityWeight = (_str) => {
};

const cleanDna = (_str) => {
var dna = Number(_str.split(":").shift());
const withoutOptions = removeQueryStrings(_str)
var dna = Number(withoutOptions.split(":").shift());
return dna;
};

Expand Down Expand Up @@ -107,6 +108,10 @@ const layersSetup = (layersOrder) => {
layerObj.options?.["opacity"] != undefined
? layerObj.options?.["opacity"]
: 1,
bypassDNA:
layerObj.options?.["bypassDNA"] !== undefined
? layerObj.options?.["bypassDNA"]
: false
}));
return layers;
};
Expand Down Expand Up @@ -231,8 +236,49 @@ const constructLayerToDna = (_dna = "", _layers = []) => {
return mappedDnaToLayers;
};

/**
* In some cases a DNA string may contain optional query parameters for options
* such as bypassing the DNA isUnique check, this function filters out those
* items without modifying the stored DNA.
*
* @param {String} _dna New DNA string
* @returns new DNA string with any items that should be filtered, removed.
*/
const filterDNAOptions = (_dna) => {
const dnaItems = _dna.split(DNA_DELIMITER)
const filteredDNA = dnaItems.filter(element => {
const query = /(\?.*$)/;
const querystring = query.exec(element);
if (!querystring) {
return true
}
const options = querystring[1].split("&").reduce((r, setting) => {
const keyPairs = setting.split("=");
return { ...r, [keyPairs[0]]: keyPairs[1] };
}, []);

return options.bypassDNA
})

return filteredDNA.join(DNA_DELIMITER)
}

/**
* Cleaning function for DNA strings. When DNA strings include an option, it
* is added to the filename with a ?setting=value query string. It needs to be
* removed to properly access the file name before Drawing.
*
* @param {String} _dna The entire newDNA string
* @returns Cleaned DNA string without querystring parameters.
*/
const removeQueryStrings = (_dna) => {
const query = /(\?.*$)/;
return _dna.replace(query, '')
}

const isDnaUnique = (_DnaList = new Set(), _dna = "") => {
return !_DnaList.has(_dna);
const _filteredDNA = filterDNAOptions(_dna);
return !_DnaList.has(_filteredDNA);
};

const createDna = (_layers) => {
Expand All @@ -249,7 +295,7 @@ const createDna = (_layers) => {
random -= layer.elements[i].weight;
if (random < 0) {
return randNum.push(
`${layer.elements[i].id}:${layer.elements[i].filename}`
`${layer.elements[i].id}:${layer.elements[i].filename}${layer.bypassDNA? '?bypassDNA=true' : ''}`
);
}
}
Expand Down Expand Up @@ -364,7 +410,7 @@ const startCreating = async () => {
)}`
);
});
dnaList.add(newDna);
dnaList.add(filterDNAOptions(newDna));
editionCount++;
abstractedIndexes.shift();
} else {
Expand Down
94 changes: 94 additions & 0 deletions utils/preview_gif.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
"use strict";

const isLocal = typeof process.pkg === "undefined";
const basePath = isLocal ? process.cwd() : path.dirname(process.execPath);
const fs = require("fs");
const path = require("path");
const { createCanvas, loadImage } = require("canvas");
const buildDir = `${basePath}/build`;
const imageDir = path.join(buildDir, "/images");
const { format, preview_gif, } = require(path.join(basePath, "/src/config.js"));
const canvas = createCanvas(format.width, format.height);
const ctx = canvas.getContext("2d");

const HashlipsGiffer = require(path.join(
basePath,
"/modules/HashlipsGiffer.js"
));
let hashlipsGiffer = null;

const loadImg = async (_img) => {
return new Promise(async (resolve) => {
const loadedImage = await loadImage(`${_img}`);
resolve({ loadedImage: loadedImage });
});
};

// read image paths
const imageList = [];
const rawdata = fs.readdirSync(imageDir).forEach(file => {
imageList.push(loadImg(`${imageDir}/${file}`));
});

const saveProjectPreviewGIF = async (_data) => {
// Extract from preview config
const { numberOfImages, order, repeat, quality, delay, imageName } = preview_gif;
// Extract from format config
const { width, height } = format;
// Prepare canvas
const previewCanvasWidth = width;
const previewCanvasHeight = height;

if(_data.length<numberOfImages) {
console.log(
`You do not have enough images to create a gif with ${numberOfImages} images.`
);
}
else {
// Shout from the mountain tops
console.log(
`Preparing a ${previewCanvasWidth}x${previewCanvasHeight} project preview with ${_data.length} images.`
);
const previewPath = `${buildDir}/${imageName}`;

ctx.clearRect(0, 0, width, height);

hashlipsGiffer = new HashlipsGiffer(
canvas,
ctx,
`${previewPath}`,
repeat,
quality,
delay
);
hashlipsGiffer.start();

await Promise.all(_data).then((renderObjectArray) => {
// Determin the order of the Images before creating the gif
if(order == 'ASC') {
// Do nothing
}
else if(order == 'DESC') {
renderObjectArray.reverse();
}
else if(order == 'MIXED') {
renderObjectArray = renderObjectArray.sort(() => Math.random() - 0.5);
}

// Reduce the size of the array of Images to the desired amount
if(parseInt(numberOfImages)>0) {
renderObjectArray = renderObjectArray.slice(0, numberOfImages);
}

renderObjectArray.forEach((renderObject, index) => {
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'source-over';
ctx.drawImage(renderObject.loadedImage, 0, 0, previewCanvasWidth, previewCanvasHeight);
hashlipsGiffer.add();
});
});
hashlipsGiffer.stop();
}
};

saveProjectPreviewGIF(imageList);

0 comments on commit 3212078

Please sign in to comment.