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.
