The profit of a firm $i$ is given by:
$$
\pi_i(p) = p q_i - C_i(q_i)
$$
where $p$ is the price, $q$_i is the output of firm $i$ and $C_i(.)$ is the cost function which differs across firms.
The first order condition gives:
$$
p = \frac{\partial C_i(q_i)}{\partial q_i} = MC_i(q_i^\ast)
$$
This shows how to obtain the optimal supply of firm $i$, i.e. where $MC(q_i^\ast)$ is equal to $p$ (see figures a,b and c in the question).
Total profits for the firm is then:
$$
\begin{align*}
\pi_i(p) &= pq_i^\ast - C_i(q_i^\ast),\\
&= \left(p - \frac{C_i(q_i^\ast)}{q_i^\ast}\right)q_i^\ast,\\
&= \left(MC(q_i^\ast) - AC(q_i^\ast)\right) q_i^\ast.
\end{align*}
$$
This corresponds to the shaded areas in figures a,b and c in the question: the areas equal the difference between $MC(q_i^\ast)$ and $AC(q_i^\ast)$ multiplied by $q_i^\ast$.
Now, consider the first order condition:
$$
p = MC_i(q_i^\ast).
$$
We can invert this function to obtain the supply curve of firm $i$:
$$
q_i(p) = q \text{ whenever } p = MC_i(q).
$$
The total supply in the market at price $p$ is determined by adding the supply curves of over all firms.
$$
Q(p) = \sum_i q_i(p).
$$
Notice that, as usual in economics, figure d in the question draws the supply and demand curves wrong, as they put $p$ on the vertical axis and $q$ on the horizontal. Mathematically, the two should be switched.
If we would do it correctly, it should look something like this:

If $p^\ast$ is the equilibrium price, then the producer surplus is given by:
$$
PS = \int_0^{p^\ast} Q(p) dp = \sum_i \int_0^{p^\ast} q_i(p) dp
$$
Now let us make a change of variables $p \to q$, where $p = MC_i(q)$. Then $dp = \frac{\partial MC_i(q)}{\partial q} dq$ so:
$$
\int_0^{p^\ast} q_i(p) dp = \int_0^{q_i^\ast} q \frac{\partial MC_i(q)}{\partial q} dq.
$$
Then use integration by parts to get:
$$
\begin{align*}
\int_0^{q_i^\ast} q \frac{\partial MC_i(q)}{\partial q} dq &= \left[q MC_i(q)\right]^{q_i^\ast}_0 - \int_0^{q_i^\ast} MC_i(q) dq,\\
&= q_i^\ast MC_i(q_i^\ast) - C_i(q_i^\ast),\\
&= p^\ast q_i^\ast - C_i(q_i^\ast) = \pi_i^\ast.
\end{align*}
$$
Here we assume $C_i(0) = 0$ and we used the first order condition to substitute $MC_i(q_i^\ast) = p^\ast$. We also used $\pi_i^\ast$ to denote the profit of firm $i$ at price $p^\ast$. From this:
$$
CS = \sum_i \int_0^{p^\ast} q_i(p) dp = \sum_i \pi_i^\ast,
$$
which shows that the consumer surplus indeed equals the sum of all profits in the industry.