guimaferreira / simulation

MIT License
0 stars 0 forks source link

Mix particles colors #6

Open guimaferreira opened 7 months ago

guimaferreira commented 7 months ago

https://chat.openai.com/c/d7fca197-c2ee-468b-b041-59ce3120ac62

function mixColors(colors) {
    // Initialize sums and count
    let sumR = 0, sumG = 0, sumB = 0, sumA = 0;
    const count = colors.length;

    // Sum up all color components
    colors.forEach(color => {
        sumR += color[0] * color[3]; // Multiply by alpha to consider transparency
        sumG += color[1] * color[3];
        sumB += color[2] * color[3];
        sumA += color[3];
    });

    // If no colors were provided, return a default transparent color
    if (count === 0) {
        return [0, 0, 0, 0];
    }

    // Calculate average of each component
    const avgR = sumR / sumA;
    const avgG = sumG / sumA;
    const avgB = sumB / sumA;
    const avgA = sumA / count;

    // Return the mixed color
    return [avgR, avgG, avgB, avgA].map(Math.round); // Round to nearest whole number
}

// Example usage:
const inputColors = [
    [255, 0, 0, 0.5],
    [0, 255, 0, 0.5],
    [0, 0, 255, 0.5]
];

const mixedColor = mixColors(inputColors);
console.log(mixedColor); // Output will be the averaged color