% cdata = draw_balls(cdata, balls)
% Render the balls in the provided color matrix 'cdata'.
% Here we pass 'cdata' as input and output so it becomes
% "pass-by-reference" style. No copies are going to be created for this
% variable.
function cdata = draw_balls(cdata, balls) %#codegen

%   Copyright 2010 The MathWorks, Inc.

% Draw each ball
for i = 1:numel(balls)
    cdata = draw_ball(cdata, balls(i));
end

% This sub-function draws a single ball.
function cdata = draw_ball(cdata, ball)
% The draw circle function requires integer coordinates, so we cast all
% double values into pure integers before handing off to the circle
% function.
cdata = draw_solid_circle(cdata, int32(ball.x), int32(ball.y), int32(ball.r), ball.color);

% This sub-function draws a solid circle with color at (x0,y0) with radius r.
% This is based on the midpoint algorithm.
function cdata = draw_solid_circle(cdata, x0, y0, r, color)
f = 1 - r;
ddF_x = 1;
ddF_y = r*-2;
x = 0;
y = r;
cdata(y0+r, x0) = color;
cdata(y0-r, x0) = color;
cdata = draw_hline(cdata, y0, x0-r, x0+r, color);
while x < y
    if f >= 0
        y = y - 1;
        ddF_y = ddF_y + 2;
        f = f + ddF_y;
    end
    x = x + 1;
    ddF_x = ddF_x + 2;
    f = f + ddF_x;
    cdata = draw_hline(cdata,y0+y,x0-x,x0+x,color);
    cdata = draw_hline(cdata,y0-y,x0-x,x0+x,color);
    cdata = draw_hline(cdata,y0+x,x0-y,x0+y,color);
    cdata = draw_hline(cdata,y0-x,x0-y,x0+y,color);
end

% Sub-function to draw a horizontal line in the color data matrix.
function cdata = draw_hline(cdata,y,x0,x1,color)
cdata(y,x0:x1) = color;
