A convexity theory for interacting gases and equilibrium crystals