A very flexible iterative method for simultaneous optimization of dynamic multileaf collimation, scanning patterns and compensation filters has been developed. The algorithm can account for and optimize almost all the degrees of freedom available in a modern radiation therapy clinic. The method has been implemented for three dimensional treatment planning. The algorithm has been tested for a number of cases where both traditional wedge filters and block collimators, and modern equipment such as scanned beams and multileaf collimators are available. It is shown that the algorithm can improve heavily on traditional uniform dose plans with respect to the probability of achieving tumor control without causing severe complications (P+) simply by finding the optimal beam weights and block collimator settings. By allowing more complex equipment to deliver the dose and by accounting for their increased flexibility during the optimization, the dose plan can be substantially improved with respect to the applied objective functions. It is demonstrated that flexible lateral collimation combined with compensators or scanned beams in most cases allow close to optimal dose delivery. Here both the calculation time and the amount of primary computer memory needed has been reduced by performing the dose calculations in a cone beam coordinate system allowing the use of approximately spatially invariant energy deposition kernels. A typical calculation time for optimization of a two-field technique in a three dimensional volume is about 20 s per iteration step on a Hewlett-Packard 735 workstation. A well converged solution is normally obtained within about 50-100 iterations or within 15-30 min.