It was originally constructed by the Teutonic Knights, a German Catholic religious order of crusaders, in a form of an Ordensburg fortress. The Order named it "Marienburg" in honour of Mary, mother of Jesus. In 1457, during the Thirteen Years’ War, it was sold by the Bohemian mercenaries to King Casimir IV of Poland in lieu of indemnities and it since served as one of the several Polish royal residences and the seat of Polish offices and institutions, interrupted by several years of Swedish occupation, and fulfilling this function until the First Partition of Poland in 1772. From then on the castle was under German rule for over 170 years until 1945.