How to derive the formula to calculate the amount of cubes in a pyramid? The pyramid looks like:

For which I managed to derive the formula for the count of cube sides (ignoring the top). This was easy by simply thinking about it as a triangle:
If we have 4 squares wide pyramid, then the total sides represented graphically looks like:
 1*4    xxxx
+2*4    xxxxxxxx
+3*4    xxxxxxxxxxxx
+4*4    xxxxxxxxxxxxxxxx

= 40 sides total.
Which is obviously a triangular area.
So I calculated half of the rectangle + remaining halves of the squares diagonally:
n*(4*n)   (4*n)
------- + ----- = 2n^2+2n
   2        2

Hurray!

Now to the real problem:
How could I visualize the count of cubes in the same pyramid in a similar way?
My brain just doesn't work in 3d. I had an idea about calculating the volume of pyramid, but I couldn't really get anywhere from there.
The answer is:
2n^3+3n^2+n
-----------
     6 

But I have now forgotten where I found this piece of magic. It works perfectly, but I don't know why.
So I would like to understand how someone came up with that formula? Preferrably in visual representation which would be easy to understand.
It's really easy to visualize as a loop (n = 4):
 1*1    x
+2*2    xxxx
+3*3    xxxxxxxxx
+4*4    xxxxxxxxxxxxxxxx

= 30 cubes total.
But I don't know how to start compressing this loop into one single formula.
Edit: I added one mandatory tag that I could think of somehow relating to this question.

Consider each level separately. On the $k$-th level ($k$ starting at $1$ and counting from the top of the pyramid), there are $k^2$ blocks. Hence we just have to compute $1^2+2^2+\cdots+n^2$.
There is a standard result that
$$\sum\limits_{k=1}^nk^2=\frac{n(n+1)(2n+1)}{6}=\frac{2n^3+3n^2+n}{6},$$
which is provable by induction or various counting methods. Here is the wikipedia article on square pyramidal numbers as they are called.

Visual proof (Taken from https://math.stackexchange.com/a/48152/160289), due to Man-Keung Siu. It appeared in the March 1984 issue of Mathematics Magazine:

(n+½)*(n+1)*n
------------- = Amount of cubes.
      3

