The output power, efficiency and stability of high power CW gyrotrons depend strongly on the quality of the electron beam generated by the magnetron injection gun. To understand deteriorating effects like low frequency oscillations or the generation of an electron beam halo, the KIT in-house beam optics code ESRAY [1] has been extended from a pure 2D electrostatic raytracing code to an advanced quasi-static particle-in-cell code, capable of handling slowly varying transient effects. In addition, a new emitter surface roughness model [2] and the treatment of secondary electrons has been implemented to achieve significantly more realistic results.