+ for(i=0; i<font->n_glyphs; ++i)
+ area += (font->glyphs[i].image.w+1)*(font->glyphs[i].image.h+1);
+
+ for(font->image.w=1;; font->image.w<<=1)
+ {
+ font->image.h = (area*5/4)/font->image.w;
+ if(font->image.h<=font->image.w)
+ break;
+ }
+ font->image.h = round_to_pot(font->image.h);
+
+ font->image.data = (char *)malloc(font->image.w*font->image.h);
+ memset(font->image.data, 255, font->image.w*font->image.h);
+ used_pixels = (char *)malloc(font->image.w*font->image.h);
+ memset(used_pixels, 0, font->image.w*font->image.h);
+ used_glyphs = (char *)malloc(font->n_glyphs);
+ memset(used_glyphs, 0, font->n_glyphs);
+
+ for(cy=0; cy<font->image.h;)
+ {
+ unsigned w;
+ unsigned x, y;
+ Glyph *glyph = NULL;
+ unsigned best_score = 0;
+ unsigned target_h = 0;
+
+ for(; (cx<font->image.w && used_pixels[cx+cy*font->image.w]); ++cx) ;
+ if(cx>=font->image.w)
+ {
+ cx = 0;
+ ++cy;
+ continue;
+ }
+ for(w=0; (cx+w<font->image.w && !used_pixels[cx+w+cy*font->image.w]); ++w) ;
+
+ for(x=0; x<cx; ++x)
+ {
+ for(y=0; (cy+y+1<font->image.h && used_pixels[cx-x+(cy+y+1)*font->image.w]); ++y) ;
+ if(y>target_h)
+ target_h = y;
+ }
+
+ for(i=0; i<font->n_glyphs; ++i)
+ {
+ Glyph *g;
+
+ g = &font->glyphs[i];
+ if(!used_glyphs[i] && g->image.w<=w)
+ {
+ unsigned score;
+
+ score = g->image.h+1;
+ if(g->image.h==target_h)
+ score *= g->image.w;
+ else
+ score += g->image.w;
+
+ if(score>best_score)
+ {
+ glyph = g;
+ best_score = score;
+ }
+ }
+ }
+
+ if(!glyph)
+ {
+ cx += w;
+ continue;
+ }
+
+ used_glyphs[glyph-font->glyphs] = 1;
+ glyph->x = cx;
+ glyph->y = cy;
+
+ for(y=0; y<glyph->image.h; ++y) for(x=0; x<glyph->image.w; ++x)
+ {
+ if(cx+x<0 || cx+x>=font->image.w || cy+y<0 || cy+y>=font->image.h)
+ continue;
+ font->image.data[cx+x+(cy+y)*font->image.w] = 255-glyph->image.data[x+y*glyph->image.w];
+ }
+ for(y=0; y<glyph->image.h+2; ++y) for(x=0; x<glyph->image.w+2; ++x)
+ {
+ if(cx+x<1 || cx+x>font->image.w || cy+y<1 || cy+y>font->image.h)
+ continue;
+ used_pixels[cx+x-1+(cy+y-1)*font->image.w] = 1;
+ }
+
+ if(cy+glyph->image.h>used_h)
+ used_h = cy+glyph->image.h;
+ }
+
+ font->image.h = round_to_pot(used_h);