| 1 |
/** |
| 2 |
* Copyright (c) 2017 The xterm.js authors. All rights reserved. |
| 3 |
* @license MIT |
| 4 |
*/ |
| 5 |
|
| 6 |
import { IColorContrastCache } from 'browser/Types'; |
| 7 |
import { DIM_OPACITY, TEXT_BASELINE } from './Constants'; |
| 8 |
import { tryDrawCustomChar } from './CustomGlyphs'; |
| 9 |
import { computeNextVariantOffset, treatGlyphAsBackgroundColor, isPowerlineGlyph, isRestrictedPowerlineGlyph, throwIfFalsy } from 'browser/renderer/shared/RendererUtils'; |
| 10 |
import { IBoundingBox, ICharAtlasConfig, IRasterizedGlyph, ITextureAtlas } from './Types'; |
| 11 |
import { NULL_COLOR, channels, color, rgba } from 'common/Color'; |
| 12 |
import { FourKeyMap } from 'common/MultiKeyMap'; |
| 13 |
import { IdleTaskQueue } from 'common/TaskQueue'; |
| 14 |
import { IColor } from 'common/Types'; |
| 15 |
import { AttributeData } from 'common/buffer/AttributeData'; |
| 16 |
import { Attributes, DEFAULT_COLOR, DEFAULT_EXT, UnderlineStyle } from 'common/buffer/Constants'; |
| 17 |
import { IUnicodeService } from 'common/services/Services'; |
| 18 |
import { Emitter } from 'vs/base/common/event'; |
| 19 |
|
| 20 |
/** |
| 21 |
* A shared object which is used to draw nothing for a particular cell. |
| 22 |
*/ |
| 23 |
const NULL_RASTERIZED_GLYPH: IRasterizedGlyph = { |
| 24 |
texturePage: 0, |
| 25 |
texturePosition: { x: 0, y: 0 }, |
| 26 |
texturePositionClipSpace: { x: 0, y: 0 }, |
| 27 |
offset: { x: 0, y: 0 }, |
| 28 |
size: { x: 0, y: 0 }, |
| 29 |
sizeClipSpace: { x: 0, y: 0 } |
| 30 |
}; |
| 31 |
|
| 32 |
const TMP_CANVAS_GLYPH_PADDING = 2; |
| 33 |
|
| 34 |
const enum Constants { |
| 35 |
/** |
| 36 |
* The amount of pixel padding to allow in each row. Setting this to zero would make the atlas |
| 37 |
* page pack as tightly as possible, but more pages would end up being created as a result. |
| 38 |
*/ |
| 39 |
ROW_PIXEL_THRESHOLD = 2, |
| 40 |
/** |
| 41 |
* The maximum texture size regardless of what the actual hardware maximum turns out to be. This |
| 42 |
* is enforced to ensure uploading the texture still finishes in a reasonable amount of time. A |
| 43 |
* 4096 squared image takes up 16MB of GPU memory. |
| 44 |
*/ |
| 45 |
FORCED_MAX_TEXTURE_SIZE = 4096 |
| 46 |
} |
| 47 |
|
| 48 |
interface ICharAtlasActiveRow { |
| 49 |
x: number; |
| 50 |
y: number; |
| 51 |
height: number; |
| 52 |
} |
| 53 |
|
| 54 |
// Work variables to avoid garbage collection |
| 55 |
let $glyph = undefined; |
| 56 |
|
| 57 |
export class TextureAtlas implements ITextureAtlas { |
| 58 |
private _didWarmUp: boolean = false; |
| 59 |
|
| 60 |
private _cacheMap: FourKeyMap<number, number, number, number, IRasterizedGlyph> = new FourKeyMap(); |
| 61 |
private _cacheMapCombined: FourKeyMap<string, number, number, number, IRasterizedGlyph> = new FourKeyMap(); |
| 62 |
|
| 63 |
// The texture that the atlas is drawn to |
| 64 |
private _pages: AtlasPage[] = []; |
| 65 |
public get pages(): { canvas: HTMLCanvasElement, version: number }[] { return this._pages; } |
| 66 |
|
| 67 |
// The set of atlas pages that can be written to |
| 68 |
private _activePages: AtlasPage[] = []; |
| 69 |
private _overflowSizePage: AtlasPage | undefined; |
| 70 |
|
| 71 |
private _tmpCanvas: HTMLCanvasElement; |
| 72 |
// A temporary context that glyphs are drawn to before being transfered to the atlas. |
| 73 |
private _tmpCtx: CanvasRenderingContext2D; |
| 74 |
|
| 75 |
private _workBoundingBox: IBoundingBox = { top: 0, left: 0, bottom: 0, right: 0 }; |
| 76 |
private _workAttributeData: AttributeData = new AttributeData(); |
| 77 |
|
| 78 |
private _textureSize: number = 512; |
| 79 |
|
| 80 |
public static maxAtlasPages: number | undefined; |
| 81 |
public static maxTextureSize: number | undefined; |
| 82 |
|
| 83 |
private readonly _onAddTextureAtlasCanvas = new Emitter<HTMLCanvasElement>(); |
| 84 |
public readonly onAddTextureAtlasCanvas = this._onAddTextureAtlasCanvas.event; |
| 85 |
private readonly _onRemoveTextureAtlasCanvas = new Emitter<HTMLCanvasElement>(); |
| 86 |
public readonly onRemoveTextureAtlasCanvas = this._onRemoveTextureAtlasCanvas.event; |
| 87 |
|
| 88 |
constructor( |
| 89 |
private readonly _document: Document, |
| 90 |
private readonly _config: ICharAtlasConfig, |
| 91 |
private readonly _unicodeService: IUnicodeService |
| 92 |
) { |
| 93 |
this._createNewPage(); |
| 94 |
this._tmpCanvas = createCanvas( |
| 95 |
_document, |
| 96 |
this._config.deviceCellWidth * 4 + TMP_CANVAS_GLYPH_PADDING * 2, |
| 97 |
this._config.deviceCellHeight + TMP_CANVAS_GLYPH_PADDING * 2 |
| 98 |
); |
| 99 |
this._tmpCtx = throwIfFalsy(this._tmpCanvas.getContext('2d', { |
| 100 |
alpha: this._config.allowTransparency, |
| 101 |
willReadFrequently: true |
| 102 |
})); |
| 103 |
} |
| 104 |
|
| 105 |
public dispose(): void { |
| 106 |
this._tmpCanvas.remove(); |
| 107 |
for (const page of this.pages) { |
| 108 |
page.canvas.remove(); |
| 109 |
} |
| 110 |
this._onAddTextureAtlasCanvas.dispose(); |
| 111 |
} |
| 112 |
|
| 113 |
public warmUp(): void { |
| 114 |
if (!this._didWarmUp) { |
| 115 |
this._doWarmUp(); |
| 116 |
this._didWarmUp = true; |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
private _doWarmUp(): void { |
| 121 |
// Pre-fill with ASCII 33-126, this is not urgent and done in idle callbacks |
| 122 |
const queue = new IdleTaskQueue(); |
| 123 |
for (let i = 33; i < 126; i++) { |
| 124 |
queue.enqueue(() => { |
| 125 |
if (!this._cacheMap.get(i, DEFAULT_COLOR, DEFAULT_COLOR, DEFAULT_EXT)) { |
| 126 |
const rasterizedGlyph = this._drawToCache(i, DEFAULT_COLOR, DEFAULT_COLOR, DEFAULT_EXT, false, undefined); |
| 127 |
this._cacheMap.set(i, DEFAULT_COLOR, DEFAULT_COLOR, DEFAULT_EXT, rasterizedGlyph); |
| 128 |
} |
| 129 |
}); |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
private _requestClearModel = false; |
| 134 |
public beginFrame(): boolean { |
| 135 |
return this._requestClearModel; |
| 136 |
} |
| 137 |
|
| 138 |
public clearTexture(): void { |
| 139 |
if (this._pages[0].currentRow.x === 0 && this._pages[0].currentRow.y === 0) { |
| 140 |
return; |
| 141 |
} |
| 142 |
for (const page of this._pages) { |
| 143 |
page.clear(); |
| 144 |
} |
| 145 |
this._cacheMap.clear(); |
| 146 |
this._cacheMapCombined.clear(); |
| 147 |
this._didWarmUp = false; |
| 148 |
} |
| 149 |
|
| 150 |
private _createNewPage(): AtlasPage { |
| 151 |
// Try merge the set of the 4 most used pages of the largest size. This is is deferred to a |
| 152 |
// microtask to ensure it does not interrupt textures that will be rendered in the current |
| 153 |
// animation frame which would result in blank rendered areas. This is actually not that |
| 154 |
// expensive relative to drawing the glyphs, so there is no need to wait for an idle callback. |
| 155 |
if (TextureAtlas.maxAtlasPages && this._pages.length >= Math.max(4, TextureAtlas.maxAtlasPages)) { |
| 156 |
// Find the set of the largest 4 images, below the maximum size, with the highest |
| 157 |
// percentages used |
| 158 |
const pagesBySize = this._pages.filter(e => { |
| 159 |
return e.canvas.width * 2 <= (TextureAtlas.maxTextureSize || Constants.FORCED_MAX_TEXTURE_SIZE); |
| 160 |
}).sort((a, b) => { |
| 161 |
if (b.canvas.width !== a.canvas.width) { |
| 162 |
return b.canvas.width - a.canvas.width; |
| 163 |
} |
| 164 |
return b.percentageUsed - a.percentageUsed; |
| 165 |
}); |
| 166 |
let sameSizeI = -1; |
| 167 |
let size = 0; |
| 168 |
for (let i = 0; i < pagesBySize.length; i++) { |
| 169 |
if (pagesBySize[i].canvas.width !== size) { |
| 170 |
sameSizeI = i; |
| 171 |
size = pagesBySize[i].canvas.width; |
| 172 |
} else if (i - sameSizeI === 3) { |
| 173 |
break; |
| 174 |
} |
| 175 |
} |
| 176 |
|
| 177 |
// Gather details of the merge |
| 178 |
const mergingPages = pagesBySize.slice(sameSizeI, sameSizeI + 4); |
| 179 |
const sortedMergingPagesIndexes = mergingPages.map(e => e.glyphs[0].texturePage).sort((a, b) => a > b ? 1 : -1); |
| 180 |
const mergedPageIndex = this.pages.length - mergingPages.length; |
| 181 |
|
| 182 |
// Merge into the new page |
| 183 |
const mergedPage = this._mergePages(mergingPages, mergedPageIndex); |
| 184 |
mergedPage.version++; |
| 185 |
|
| 186 |
// Delete the pages, shifting glyph texture pages as needed |
| 187 |
for (let i = sortedMergingPagesIndexes.length - 1; i >= 0; i--) { |
| 188 |
this._deletePage(sortedMergingPagesIndexes[i]); |
| 189 |
} |
| 190 |
|
| 191 |
// Add the new merged page to the end |
| 192 |
this.pages.push(mergedPage); |
| 193 |
|
| 194 |
// Request the model to be cleared to refresh all texture pages. |
| 195 |
this._requestClearModel = true; |
| 196 |
this._onAddTextureAtlasCanvas.fire(mergedPage.canvas); |
| 197 |
} |
| 198 |
|
| 199 |
// All new atlas pages are created small as they are highly dynamic |
| 200 |
const newPage = new AtlasPage(this._document, this._textureSize); |
| 201 |
this._pages.push(newPage); |
| 202 |
this._activePages.push(newPage); |
| 203 |
this._onAddTextureAtlasCanvas.fire(newPage.canvas); |
| 204 |
return newPage; |
| 205 |
} |
| 206 |
|
| 207 |
private _mergePages(mergingPages: AtlasPage[], mergedPageIndex: number): AtlasPage { |
| 208 |
const mergedSize = mergingPages[0].canvas.width * 2; |
| 209 |
const mergedPage = new AtlasPage(this._document, mergedSize, mergingPages); |
| 210 |
for (const [i, p] of mergingPages.entries()) { |
| 211 |
const xOffset = i * p.canvas.width % mergedSize; |
| 212 |
const yOffset = Math.floor(i / 2) * p.canvas.height; |
| 213 |
mergedPage.ctx.drawImage(p.canvas, xOffset, yOffset); |
| 214 |
for (const g of p.glyphs) { |
| 215 |
g.texturePage = mergedPageIndex; |
| 216 |
g.sizeClipSpace.x = g.size.x / mergedSize; |
| 217 |
g.sizeClipSpace.y = g.size.y / mergedSize; |
| 218 |
g.texturePosition.x += xOffset; |
| 219 |
g.texturePosition.y += yOffset; |
| 220 |
g.texturePositionClipSpace.x = g.texturePosition.x / mergedSize; |
| 221 |
g.texturePositionClipSpace.y = g.texturePosition.y / mergedSize; |
| 222 |
} |
| 223 |
|
| 224 |
this._onRemoveTextureAtlasCanvas.fire(p.canvas); |
| 225 |
|
| 226 |
// Remove the merging page from active pages if it was there |
| 227 |
const index = this._activePages.indexOf(p); |
| 228 |
if (index !== -1) { |
| 229 |
this._activePages.splice(index, 1); |
| 230 |
} |
| 231 |
} |
| 232 |
return mergedPage; |
| 233 |
} |
| 234 |
|
| 235 |
private _deletePage(pageIndex: number): void { |
| 236 |
this._pages.splice(pageIndex, 1); |
| 237 |
for (let j = pageIndex; j < this._pages.length; j++) { |
| 238 |
const adjustingPage = this._pages[j]; |
| 239 |
for (const g of adjustingPage.glyphs) { |
| 240 |
g.texturePage--; |
| 241 |
} |
| 242 |
adjustingPage.version++; |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
public getRasterizedGlyphCombinedChar(chars: string, bg: number, fg: number, ext: number, restrictToCellHeight: boolean, domContainer: HTMLElement | undefined): IRasterizedGlyph { |
| 247 |
return this._getFromCacheMap(this._cacheMapCombined, chars, bg, fg, ext, restrictToCellHeight, domContainer); |
| 248 |
} |
| 249 |
|
| 250 |
public getRasterizedGlyph(code: number, bg: number, fg: number, ext: number, restrictToCellHeight: boolean, domContainer: HTMLElement | undefined): IRasterizedGlyph { |
| 251 |
return this._getFromCacheMap(this._cacheMap, code, bg, fg, ext, restrictToCellHeight, domContainer); |
| 252 |
} |
| 253 |
|
| 254 |
/** |
| 255 |
* Gets the glyphs texture coords, drawing the texture if it's not already |
| 256 |
*/ |
| 257 |
private _getFromCacheMap( |
| 258 |
cacheMap: FourKeyMap<string | number, number, number, number, IRasterizedGlyph>, |
| 259 |
key: string | number, |
| 260 |
bg: number, |
| 261 |
fg: number, |
| 262 |
ext: number, |
| 263 |
restrictToCellHeight: boolean, |
| 264 |
domContainer: HTMLElement | undefined |
| 265 |
): IRasterizedGlyph { |
| 266 |
$glyph = cacheMap.get(key, bg, fg, ext); |
| 267 |
if (!$glyph) { |
| 268 |
$glyph = this._drawToCache(key, bg, fg, ext, restrictToCellHeight, domContainer); |
| 269 |
cacheMap.set(key, bg, fg, ext, $glyph); |
| 270 |
} |
| 271 |
return $glyph; |
| 272 |
} |
| 273 |
|
| 274 |
private _getColorFromAnsiIndex(idx: number): IColor { |
| 275 |
if (idx >= this._config.colors.ansi.length) { |
| 276 |
throw new Error('No color found for idx ' + idx); |
| 277 |
} |
| 278 |
return this._config.colors.ansi[idx]; |
| 279 |
} |
| 280 |
|
| 281 |
private _getBackgroundColor(bgColorMode: number, bgColor: number, inverse: boolean, dim: boolean): IColor { |
| 282 |
if (this._config.allowTransparency) { |
| 283 |
// The background color might have some transparency, so we need to render it as fully |
| 284 |
// transparent in the atlas. Otherwise we'd end up drawing the transparent background twice |
| 285 |
// around the anti-aliased edges of the glyph, and it would look too dark. |
| 286 |
return NULL_COLOR; |
| 287 |
} |
| 288 |
|
| 289 |
let result: IColor; |
| 290 |
switch (bgColorMode) { |
| 291 |
case Attributes.CM_P16: |
| 292 |
case Attributes.CM_P256: |
| 293 |
result = this._getColorFromAnsiIndex(bgColor); |
| 294 |
break; |
| 295 |
case Attributes.CM_RGB: |
| 296 |
const arr = AttributeData.toColorRGB(bgColor); |
| 297 |
result = channels.toColor(arr[0], arr[1], arr[2]); |
| 298 |
break; |
| 299 |
case Attributes.CM_DEFAULT: |
| 300 |
default: |
| 301 |
if (inverse) { |
| 302 |
result = color.opaque(this._config.colors.foreground); |
| 303 |
} else { |
| 304 |
result = this._config.colors.background; |
| 305 |
} |
| 306 |
break; |
| 307 |
} |
| 308 |
|
| 309 |
// Ignore alpha channel when allowTransparency is false |
| 310 |
if (!this._config.allowTransparency) { |
| 311 |
result = color.opaque(result); |
| 312 |
} |
| 313 |
|
| 314 |
return result; |
| 315 |
} |
| 316 |
|
| 317 |
private _getForegroundColor(bg: number, bgColorMode: number, bgColor: number, fg: number, fgColorMode: number, fgColor: number, inverse: boolean, dim: boolean, bold: boolean, excludeFromContrastRatioDemands: boolean): IColor { |
| 318 |
const minimumContrastColor = this._getMinimumContrastColor(bg, bgColorMode, bgColor, fg, fgColorMode, fgColor, inverse, bold, dim, excludeFromContrastRatioDemands); |
| 319 |
if (minimumContrastColor) { |
| 320 |
return minimumContrastColor; |
| 321 |
} |
| 322 |
|
| 323 |
let result: IColor; |
| 324 |
switch (fgColorMode) { |
| 325 |
case Attributes.CM_P16: |
| 326 |
case Attributes.CM_P256: |
| 327 |
if (this._config.drawBoldTextInBrightColors && bold && fgColor < 8) { |
| 328 |
fgColor += 8; |
| 329 |
} |
| 330 |
result = this._getColorFromAnsiIndex(fgColor); |
| 331 |
break; |
| 332 |
case Attributes.CM_RGB: |
| 333 |
const arr = AttributeData.toColorRGB(fgColor); |
| 334 |
result = channels.toColor(arr[0], arr[1], arr[2]); |
| 335 |
break; |
| 336 |
case Attributes.CM_DEFAULT: |
| 337 |
default: |
| 338 |
if (inverse) { |
| 339 |
result = this._config.colors.background; |
| 340 |
} else { |
| 341 |
result = this._config.colors.foreground; |
| 342 |
} |
| 343 |
} |
| 344 |
|
| 345 |
// Always use an opaque color regardless of allowTransparency |
| 346 |
if (this._config.allowTransparency) { |
| 347 |
result = color.opaque(result); |
| 348 |
} |
| 349 |
|
| 350 |
// Apply dim to the color, opacity is fine to use for the foreground color |
| 351 |
if (dim) { |
| 352 |
result = color.multiplyOpacity(result, DIM_OPACITY); |
| 353 |
} |
| 354 |
|
| 355 |
return result; |
| 356 |
} |
| 357 |
|
| 358 |
private _resolveBackgroundRgba(bgColorMode: number, bgColor: number, inverse: boolean): number { |
| 359 |
switch (bgColorMode) { |
| 360 |
case Attributes.CM_P16: |
| 361 |
case Attributes.CM_P256: |
| 362 |
return this._getColorFromAnsiIndex(bgColor).rgba; |
| 363 |
case Attributes.CM_RGB: |
| 364 |
return bgColor << 8; |
| 365 |
case Attributes.CM_DEFAULT: |
| 366 |
default: |
| 367 |
if (inverse) { |
| 368 |
return this._config.colors.foreground.rgba; |
| 369 |
} |
| 370 |
return this._config.colors.background.rgba; |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
private _resolveForegroundRgba(fgColorMode: number, fgColor: number, inverse: boolean, bold: boolean): number { |
| 375 |
switch (fgColorMode) { |
| 376 |
case Attributes.CM_P16: |
| 377 |
case Attributes.CM_P256: |
| 378 |
if (this._config.drawBoldTextInBrightColors && bold && fgColor < 8) { |
| 379 |
fgColor += 8; |
| 380 |
} |
| 381 |
return this._getColorFromAnsiIndex(fgColor).rgba; |
| 382 |
case Attributes.CM_RGB: |
| 383 |
return fgColor << 8; |
| 384 |
case Attributes.CM_DEFAULT: |
| 385 |
default: |
| 386 |
if (inverse) { |
| 387 |
return this._config.colors.background.rgba; |
| 388 |
} |
| 389 |
return this._config.colors.foreground.rgba; |
| 390 |
} |
| 391 |
} |
| 392 |
|
| 393 |
private _getMinimumContrastColor(bg: number, bgColorMode: number, bgColor: number, fg: number, fgColorMode: number, fgColor: number, inverse: boolean, bold: boolean, dim: boolean, excludeFromContrastRatioDemands: boolean): IColor | undefined { |
| 394 |
if (this._config.minimumContrastRatio === 1 || excludeFromContrastRatioDemands) { |
| 395 |
return undefined; |
| 396 |
} |
| 397 |
|
| 398 |
// Try get from cache first |
| 399 |
const cache = this._getContrastCache(dim); |
| 400 |
const adjustedColor = cache.getColor(bg, fg); |
| 401 |
if (adjustedColor !== undefined) { |
| 402 |
return adjustedColor || undefined; |
| 403 |
} |
| 404 |
|
| 405 |
const bgRgba = this._resolveBackgroundRgba(bgColorMode, bgColor, inverse); |
| 406 |
const fgRgba = this._resolveForegroundRgba(fgColorMode, fgColor, inverse, bold); |
| 407 |
// Dim cells only require half the contrast, otherwise they wouldn't be distinguishable from |
| 408 |
// non-dim cells |
| 409 |
const result = rgba.ensureContrastRatio(bgRgba, fgRgba, this._config.minimumContrastRatio / (dim ? 2 : 1)); |
| 410 |
|
| 411 |
if (!result) { |
| 412 |
cache.setColor(bg, fg, null); |
| 413 |
return undefined; |
| 414 |
} |
| 415 |
|
| 416 |
const color = channels.toColor( |
| 417 |
(result >> 24) & 0xFF, |
| 418 |
(result >> 16) & 0xFF, |
| 419 |
(result >> 8) & 0xFF |
| 420 |
); |
| 421 |
cache.setColor(bg, fg, color); |
| 422 |
|
| 423 |
return color; |
| 424 |
} |
| 425 |
|
| 426 |
private _getContrastCache(dim: boolean): IColorContrastCache { |
| 427 |
if (dim) { |
| 428 |
return this._config.colors.halfContrastCache; |
| 429 |
} |
| 430 |
return this._config.colors.contrastCache; |
| 431 |
} |
| 432 |
|
| 433 |
private _drawToCache(codeOrChars: number | string, bg: number, fg: number, ext: number, restrictToCellHeight: boolean, domContainer: HTMLElement | undefined): IRasterizedGlyph { |
| 434 |
const chars = typeof codeOrChars === 'number' ? String.fromCharCode(codeOrChars) : codeOrChars; |
| 435 |
|
| 436 |
// Uncomment for debugging |
| 437 |
// console.log(`draw to cache "${chars}"`, bg, fg, ext); |
| 438 |
|
| 439 |
// Attach the canvas to the DOM in order to inherit font-feature-settings |
| 440 |
// from the parent elements. This is necessary for ligatures and variants to |
| 441 |
// work. |
| 442 |
if (domContainer && this._tmpCanvas.parentElement !== domContainer) { |
| 443 |
this._tmpCanvas.style.display = 'none'; |
| 444 |
domContainer.append(this._tmpCanvas); |
| 445 |
} |
| 446 |
|
| 447 |
// Allow 1 cell width per character, with a minimum of 2 (CJK), plus some padding. This is used |
| 448 |
// to draw the glyph to the canvas as well as to restrict the bounding box search to ensure |
| 449 |
// giant ligatures (eg. =====>) don't impact overall performance. |
| 450 |
const allowedWidth = Math.min(this._config.deviceCellWidth * Math.max(chars.length, 2) + TMP_CANVAS_GLYPH_PADDING * 2, this._config.deviceMaxTextureSize); |
| 451 |
if (this._tmpCanvas.width < allowedWidth) { |
| 452 |
this._tmpCanvas.width = allowedWidth; |
| 453 |
} |
| 454 |
// Include line height when drawing glyphs |
| 455 |
const allowedHeight = Math.min(this._config.deviceCellHeight + TMP_CANVAS_GLYPH_PADDING * 4, this._textureSize); |
| 456 |
if (this._tmpCanvas.height < allowedHeight) { |
| 457 |
this._tmpCanvas.height = allowedHeight; |
| 458 |
} |
| 459 |
this._tmpCtx.save(); |
| 460 |
|
| 461 |
this._workAttributeData.fg = fg; |
| 462 |
this._workAttributeData.bg = bg; |
| 463 |
this._workAttributeData.extended.ext = ext; |
| 464 |
|
| 465 |
const invisible = !!this._workAttributeData.isInvisible(); |
| 466 |
if (invisible) { |
| 467 |
return NULL_RASTERIZED_GLYPH; |
| 468 |
} |
| 469 |
|
| 470 |
const bold = !!this._workAttributeData.isBold(); |
| 471 |
const inverse = !!this._workAttributeData.isInverse(); |
| 472 |
const dim = !!this._workAttributeData.isDim(); |
| 473 |
const italic = !!this._workAttributeData.isItalic(); |
| 474 |
const underline = !!this._workAttributeData.isUnderline(); |
| 475 |
const strikethrough = !!this._workAttributeData.isStrikethrough(); |
| 476 |
const overline = !!this._workAttributeData.isOverline(); |
| 477 |
let fgColor = this._workAttributeData.getFgColor(); |
| 478 |
let fgColorMode = this._workAttributeData.getFgColorMode(); |
| 479 |
let bgColor = this._workAttributeData.getBgColor(); |
| 480 |
let bgColorMode = this._workAttributeData.getBgColorMode(); |
| 481 |
if (inverse) { |
| 482 |
const temp = fgColor; |
| 483 |
fgColor = bgColor; |
| 484 |
bgColor = temp; |
| 485 |
const temp2 = fgColorMode; |
| 486 |
fgColorMode = bgColorMode; |
| 487 |
bgColorMode = temp2; |
| 488 |
} |
| 489 |
|
| 490 |
// draw the background |
| 491 |
const backgroundColor = this._getBackgroundColor(bgColorMode, bgColor, inverse, dim); |
| 492 |
// Use a 'copy' composite operation to clear any existing glyph out of _tmpCtxWithAlpha, |
| 493 |
// regardless of transparency in backgroundColor |
| 494 |
this._tmpCtx.globalCompositeOperation = 'copy'; |
| 495 |
this._tmpCtx.fillStyle = backgroundColor.css; |
| 496 |
this._tmpCtx.fillRect(0, 0, this._tmpCanvas.width, this._tmpCanvas.height); |
| 497 |
this._tmpCtx.globalCompositeOperation = 'source-over'; |
| 498 |
|
| 499 |
// draw the foreground/glyph |
| 500 |
const fontWeight = bold ? this._config.fontWeightBold : this._config.fontWeight; |
| 501 |
const fontStyle = italic ? 'italic' : ''; |
| 502 |
this._tmpCtx.font = |
| 503 |
`${fontStyle} ${fontWeight} ${this._config.fontSize * this._config.devicePixelRatio}px ${this._config.fontFamily}`; |
| 504 |
this._tmpCtx.textBaseline = TEXT_BASELINE; |
| 505 |
|
| 506 |
const powerlineGlyph = chars.length === 1 && isPowerlineGlyph(chars.charCodeAt(0)); |
| 507 |
const restrictedPowerlineGlyph = chars.length === 1 && isRestrictedPowerlineGlyph(chars.charCodeAt(0)); |
| 508 |
const foregroundColor = this._getForegroundColor(bg, bgColorMode, bgColor, fg, fgColorMode, fgColor, inverse, dim, bold, treatGlyphAsBackgroundColor(chars.charCodeAt(0))); |
| 509 |
this._tmpCtx.fillStyle = foregroundColor.css; |
| 510 |
|
| 511 |
// For powerline glyphs left/top padding is excluded (https://github.com/microsoft/vscode/issues/120129) |
| 512 |
const padding = restrictedPowerlineGlyph ? 0 : TMP_CANVAS_GLYPH_PADDING * 2; |
| 513 |
|
| 514 |
// Draw custom characters if applicable |
| 515 |
let customGlyph = false; |
| 516 |
if (this._config.customGlyphs !== false) { |
| 517 |
customGlyph = tryDrawCustomChar(this._tmpCtx, chars, padding, padding, this._config.deviceCellWidth, this._config.deviceCellHeight, this._config.fontSize, this._config.devicePixelRatio); |
| 518 |
} |
| 519 |
|
| 520 |
// Whether to clear pixels based on a threshold difference between the glyph color and the |
| 521 |
// background color. This should be disabled when the glyph contains multiple colors such as |
| 522 |
// underline colors to prevent important colors could get cleared. |
| 523 |
let enableClearThresholdCheck = !powerlineGlyph; |
| 524 |
|
| 525 |
let chWidth: number; |
| 526 |
if (typeof codeOrChars === 'number') { |
| 527 |
chWidth = this._unicodeService.wcwidth(codeOrChars); |
| 528 |
} else { |
| 529 |
chWidth = this._unicodeService.getStringCellWidth(codeOrChars); |
| 530 |
} |
| 531 |
|
| 532 |
// Draw underline |
| 533 |
if (underline) { |
| 534 |
this._tmpCtx.save(); |
| 535 |
const lineWidth = Math.max(1, Math.floor(this._config.fontSize * this._config.devicePixelRatio / 15)); |
| 536 |
// When the line width is odd, draw at a 0.5 position |
| 537 |
const yOffset = lineWidth % 2 === 1 ? 0.5 : 0; |
| 538 |
this._tmpCtx.lineWidth = lineWidth; |
| 539 |
|
| 540 |
// Underline color |
| 541 |
if (this._workAttributeData.isUnderlineColorDefault()) { |
| 542 |
this._tmpCtx.strokeStyle = this._tmpCtx.fillStyle; |
| 543 |
} else if (this._workAttributeData.isUnderlineColorRGB()) { |
| 544 |
enableClearThresholdCheck = false; |
| 545 |
this._tmpCtx.strokeStyle = `rgb(${AttributeData.toColorRGB(this._workAttributeData.getUnderlineColor()).join(',')})`; |
| 546 |
} else { |
| 547 |
enableClearThresholdCheck = false; |
| 548 |
let fg = this._workAttributeData.getUnderlineColor(); |
| 549 |
if (this._config.drawBoldTextInBrightColors && this._workAttributeData.isBold() && fg < 8) { |
| 550 |
fg += 8; |
| 551 |
} |
| 552 |
this._tmpCtx.strokeStyle = this._getColorFromAnsiIndex(fg).css; |
| 553 |
} |
| 554 |
|
| 555 |
// Underline style/stroke |
| 556 |
this._tmpCtx.beginPath(); |
| 557 |
const xLeft = padding; |
| 558 |
const yTop = Math.ceil(padding + this._config.deviceCharHeight) - yOffset - (restrictToCellHeight ? lineWidth * 2 : 0); |
| 559 |
const yMid = yTop + lineWidth; |
| 560 |
const yBot = yTop + lineWidth * 2; |
| 561 |
let nextOffset = this._workAttributeData.getUnderlineVariantOffset(); |
| 562 |
|
| 563 |
for (let i = 0; i < chWidth; i++) { |
| 564 |
this._tmpCtx.save(); |
| 565 |
const xChLeft = xLeft + i * this._config.deviceCellWidth; |
| 566 |
const xChRight = xLeft + (i + 1) * this._config.deviceCellWidth; |
| 567 |
const xChMid = xChLeft + this._config.deviceCellWidth / 2; |
| 568 |
switch (this._workAttributeData.extended.underlineStyle) { |
| 569 |
case UnderlineStyle.DOUBLE: |
| 570 |
this._tmpCtx.moveTo(xChLeft, yTop); |
| 571 |
this._tmpCtx.lineTo(xChRight, yTop); |
| 572 |
this._tmpCtx.moveTo(xChLeft, yBot); |
| 573 |
this._tmpCtx.lineTo(xChRight, yBot); |
| 574 |
break; |
| 575 |
case UnderlineStyle.CURLY: |
| 576 |
// Choose the bezier top and bottom based on the device pixel ratio, the curly line is |
| 577 |
// made taller when the line width is as otherwise it's not very clear otherwise. |
| 578 |
const yCurlyBot = lineWidth <= 1 ? yBot : Math.ceil(padding + this._config.deviceCharHeight - lineWidth / 2) - yOffset; |
| 579 |
const yCurlyTop = lineWidth <= 1 ? yTop : Math.ceil(padding + this._config.deviceCharHeight + lineWidth / 2) - yOffset; |
| 580 |
// Clip the left and right edges of the underline such that it can be drawn just outside |
| 581 |
// the edge of the cell to ensure a continuous stroke when there are multiple underlined |
| 582 |
// glyphs adjacent to one another. |
| 583 |
const clipRegion = new Path2D(); |
| 584 |
clipRegion.rect(xChLeft, yTop, this._config.deviceCellWidth, yBot - yTop); |
| 585 |
this._tmpCtx.clip(clipRegion); |
| 586 |
// Start 1/2 cell before and end 1/2 cells after to ensure a smooth curve with other |
| 587 |
// cells |
| 588 |
this._tmpCtx.moveTo(xChLeft - this._config.deviceCellWidth / 2, yMid); |
| 589 |
this._tmpCtx.bezierCurveTo( |
| 590 |
xChLeft - this._config.deviceCellWidth / 2, yCurlyTop, |
| 591 |
xChLeft, yCurlyTop, |
| 592 |
xChLeft, yMid |
| 593 |
); |
| 594 |
this._tmpCtx.bezierCurveTo( |
| 595 |
xChLeft, yCurlyBot, |
| 596 |
xChMid, yCurlyBot, |
| 597 |
xChMid, yMid |
| 598 |
); |
| 599 |
this._tmpCtx.bezierCurveTo( |
| 600 |
xChMid, yCurlyTop, |
| 601 |
xChRight, yCurlyTop, |
| 602 |
xChRight, yMid |
| 603 |
); |
| 604 |
this._tmpCtx.bezierCurveTo( |
| 605 |
xChRight, yCurlyBot, |
| 606 |
xChRight + this._config.deviceCellWidth / 2, yCurlyBot, |
| 607 |
xChRight + this._config.deviceCellWidth / 2, yMid |
| 608 |
); |
| 609 |
break; |
| 610 |
case UnderlineStyle.DOTTED: |
| 611 |
const offsetWidth = nextOffset === 0 ? 0 : |
| 612 |
(nextOffset >= lineWidth ? lineWidth * 2 - nextOffset : lineWidth - nextOffset); |
| 613 |
// a line and a gap. |
| 614 |
const isLineStart = nextOffset >= lineWidth ? false : true; |
| 615 |
if (isLineStart === false || offsetWidth === 0) { |
| 616 |
this._tmpCtx.setLineDash([Math.round(lineWidth), Math.round(lineWidth)]); |
| 617 |
this._tmpCtx.moveTo(xChLeft + offsetWidth, yTop); |
| 618 |
this._tmpCtx.lineTo(xChRight, yTop); |
| 619 |
} else { |
| 620 |
this._tmpCtx.setLineDash([Math.round(lineWidth), Math.round(lineWidth)]); |
| 621 |
this._tmpCtx.moveTo(xChLeft, yTop); |
| 622 |
this._tmpCtx.lineTo(xChLeft + offsetWidth, yTop); |
| 623 |
this._tmpCtx.moveTo(xChLeft + offsetWidth + lineWidth, yTop); |
| 624 |
this._tmpCtx.lineTo(xChRight, yTop); |
| 625 |
} |
| 626 |
nextOffset = computeNextVariantOffset(xChRight - xChLeft, lineWidth, nextOffset); |
| 627 |
break; |
| 628 |
case UnderlineStyle.DASHED: |
| 629 |
const lineRatio = 0.6; |
| 630 |
const gapRatio = 0.3; |
| 631 |
// End line ratio is approximately equal to 0.1 |
| 632 |
const xChWidth = xChRight - xChLeft; |
| 633 |
const line = Math.floor(lineRatio * xChWidth); |
| 634 |
const gap = Math.floor(gapRatio * xChWidth); |
| 635 |
const end = xChWidth - line - gap; |
| 636 |
this._tmpCtx.setLineDash([line, gap, end]); |
| 637 |
this._tmpCtx.moveTo(xChLeft, yTop); |
| 638 |
this._tmpCtx.lineTo(xChRight, yTop); |
| 639 |
break; |
| 640 |
case UnderlineStyle.SINGLE: |
| 641 |
default: |
| 642 |
this._tmpCtx.moveTo(xChLeft, yTop); |
| 643 |
this._tmpCtx.lineTo(xChRight, yTop); |
| 644 |
break; |
| 645 |
} |
| 646 |
this._tmpCtx.stroke(); |
| 647 |
this._tmpCtx.restore(); |
| 648 |
} |
| 649 |
this._tmpCtx.restore(); |
| 650 |
|
| 651 |
// Draw stroke in the background color for non custom characters in order to give an outline |
| 652 |
// between the text and the underline. Only do this when font size is >= 12 as the underline |
| 653 |
// looks odd when the font size is too small |
| 654 |
if (!customGlyph && this._config.fontSize >= 12) { |
| 655 |
// This only works when transparency is disabled because it's not clear how to clear stroked |
| 656 |
// text |
| 657 |
if (!this._config.allowTransparency && chars !== ' ') { |
| 658 |
// Measure the text, only draw the stroke if there is a descent beyond an alphabetic text |
| 659 |
// baseline |
| 660 |
this._tmpCtx.save(); |
| 661 |
this._tmpCtx.textBaseline = 'alphabetic'; |
| 662 |
const metrics = this._tmpCtx.measureText(chars); |
| 663 |
this._tmpCtx.restore(); |
| 664 |
if ('actualBoundingBoxDescent' in metrics && metrics.actualBoundingBoxDescent > 0) { |
| 665 |
// This translates to 1/2 the line width in either direction |
| 666 |
this._tmpCtx.save(); |
| 667 |
// Clip the region to only draw in valid pixels near the underline to avoid a slight |
| 668 |
// outline around the whole glyph, as well as additional pixels in the glyph at the top |
| 669 |
// which would increase GPU memory demands |
| 670 |
const clipRegion = new Path2D(); |
| 671 |
clipRegion.rect(xLeft, yTop - Math.ceil(lineWidth / 2), this._config.deviceCellWidth * chWidth, yBot - yTop + Math.ceil(lineWidth / 2)); |
| 672 |
this._tmpCtx.clip(clipRegion); |
| 673 |
this._tmpCtx.lineWidth = this._config.devicePixelRatio * 3; |
| 674 |
this._tmpCtx.strokeStyle = backgroundColor.css; |
| 675 |
this._tmpCtx.strokeText(chars, padding, padding + this._config.deviceCharHeight); |
| 676 |
this._tmpCtx.restore(); |
| 677 |
} |
| 678 |
} |
| 679 |
} |
| 680 |
} |
| 681 |
|
| 682 |
// Overline |
| 683 |
if (overline) { |
| 684 |
const lineWidth = Math.max(1, Math.floor(this._config.fontSize * this._config.devicePixelRatio / 15)); |
| 685 |
const yOffset = lineWidth % 2 === 1 ? 0.5 : 0; |
| 686 |
this._tmpCtx.lineWidth = lineWidth; |
| 687 |
this._tmpCtx.strokeStyle = this._tmpCtx.fillStyle; |
| 688 |
this._tmpCtx.beginPath(); |
| 689 |
this._tmpCtx.moveTo(padding, padding + yOffset); |
| 690 |
this._tmpCtx.lineTo(padding + this._config.deviceCharWidth * chWidth, padding + yOffset); |
| 691 |
this._tmpCtx.stroke(); |
| 692 |
} |
| 693 |
|
| 694 |
// Draw the character |
| 695 |
if (!customGlyph) { |
| 696 |
this._tmpCtx.fillText(chars, padding, padding + this._config.deviceCharHeight); |
| 697 |
} |
| 698 |
|
| 699 |
// If this character is underscore and beyond the cell bounds, shift it up until it is visible |
| 700 |
// even on the bottom row, try for a maximum of 5 pixels. |
| 701 |
if (chars === '_' && !this._config.allowTransparency) { |
| 702 |
let isBeyondCellBounds = clearColor(this._tmpCtx.getImageData(padding, padding, this._config.deviceCellWidth, this._config.deviceCellHeight), backgroundColor, foregroundColor, enableClearThresholdCheck); |
| 703 |
if (isBeyondCellBounds) { |
| 704 |
for (let offset = 1; offset <= 5; offset++) { |
| 705 |
this._tmpCtx.save(); |
| 706 |
this._tmpCtx.fillStyle = backgroundColor.css; |
| 707 |
this._tmpCtx.fillRect(0, 0, this._tmpCanvas.width, this._tmpCanvas.height); |
| 708 |
this._tmpCtx.restore(); |
| 709 |
this._tmpCtx.fillText(chars, padding, padding + this._config.deviceCharHeight - offset); |
| 710 |
isBeyondCellBounds = clearColor(this._tmpCtx.getImageData(padding, padding, this._config.deviceCellWidth, this._config.deviceCellHeight), backgroundColor, foregroundColor, enableClearThresholdCheck); |
| 711 |
if (!isBeyondCellBounds) { |
| 712 |
break; |
| 713 |
} |
| 714 |
} |
| 715 |
} |
| 716 |
} |
| 717 |
|
| 718 |
// Draw strokethrough |
| 719 |
if (strikethrough) { |
| 720 |
const lineWidth = Math.max(1, Math.floor(this._config.fontSize * this._config.devicePixelRatio / 10)); |
| 721 |
const yOffset = this._tmpCtx.lineWidth % 2 === 1 ? 0.5 : 0; // When the width is odd, draw at 0.5 position |
| 722 |
this._tmpCtx.lineWidth = lineWidth; |
| 723 |
this._tmpCtx.strokeStyle = this._tmpCtx.fillStyle; |
| 724 |
this._tmpCtx.beginPath(); |
| 725 |
this._tmpCtx.moveTo(padding, padding + Math.floor(this._config.deviceCharHeight / 2) - yOffset); |
| 726 |
this._tmpCtx.lineTo(padding + this._config.deviceCharWidth * chWidth, padding + Math.floor(this._config.deviceCharHeight / 2) - yOffset); |
| 727 |
this._tmpCtx.stroke(); |
| 728 |
} |
| 729 |
|
| 730 |
this._tmpCtx.restore(); |
| 731 |
|
| 732 |
// clear the background from the character to avoid issues with drawing over the previous |
| 733 |
// character if it extends past it's bounds |
| 734 |
const imageData = this._tmpCtx.getImageData( |
| 735 |
0, 0, this._tmpCanvas.width, this._tmpCanvas.height |
| 736 |
); |
| 737 |
|
| 738 |
// Clear out the background color and determine if the glyph is empty. |
| 739 |
let isEmpty: boolean; |
| 740 |
if (!this._config.allowTransparency) { |
| 741 |
isEmpty = clearColor(imageData, backgroundColor, foregroundColor, enableClearThresholdCheck); |
| 742 |
} else { |
| 743 |
isEmpty = checkCompletelyTransparent(imageData); |
| 744 |
} |
| 745 |
|
| 746 |
// Handle empty glyphs |
| 747 |
if (isEmpty) { |
| 748 |
return NULL_RASTERIZED_GLYPH; |
| 749 |
} |
| 750 |
|
| 751 |
const rasterizedGlyph = this._findGlyphBoundingBox(imageData, this._workBoundingBox, allowedWidth, restrictedPowerlineGlyph, customGlyph, padding); |
| 752 |
|
| 753 |
// Find the best atlas row to use |
| 754 |
let activePage: AtlasPage; |
| 755 |
let activeRow: ICharAtlasActiveRow; |
| 756 |
while (true) { |
| 757 |
// If there are no active pages (the last smallest 4 were merged), create a new one |
| 758 |
if (this._activePages.length === 0) { |
| 759 |
const newPage = this._createNewPage(); |
| 760 |
activePage = newPage; |
| 761 |
activeRow = newPage.currentRow; |
| 762 |
activeRow.height = rasterizedGlyph.size.y; |
| 763 |
break; |
| 764 |
} |
| 765 |
|
| 766 |
// Get the best current row from all active pages |
| 767 |
activePage = this._activePages[this._activePages.length - 1]; |
| 768 |
activeRow = activePage.currentRow; |
| 769 |
for (const p of this._activePages) { |
| 770 |
if (rasterizedGlyph.size.y <= p.currentRow.height) { |
| 771 |
activePage = p; |
| 772 |
activeRow = p.currentRow; |
| 773 |
} |
| 774 |
} |
| 775 |
|
| 776 |
// TODO: This algorithm could be simplified: |
| 777 |
// - Search for the page with ROW_PIXEL_THRESHOLD in mind |
| 778 |
// - Keep track of current/fixed rows in a Map |
| 779 |
|
| 780 |
// Replace the best current row with a fixed row if there is one at least as good as the |
| 781 |
// current row. Search in reverse to prioritize filling in older pages. |
| 782 |
for (let i = this._activePages.length - 1; i >= 0; i--) { |
| 783 |
for (const row of this._activePages[i].fixedRows) { |
| 784 |
if (row.height <= activeRow.height && rasterizedGlyph.size.y <= row.height) { |
| 785 |
activePage = this._activePages[i]; |
| 786 |
activeRow = row; |
| 787 |
} |
| 788 |
} |
| 789 |
} |
| 790 |
|
| 791 |
// Create a new page for oversized glyphs as they come up |
| 792 |
if (rasterizedGlyph.size.x > this._textureSize) { |
| 793 |
if (!this._overflowSizePage) { |
| 794 |
this._overflowSizePage = new AtlasPage(this._document, this._config.deviceMaxTextureSize); |
| 795 |
this.pages.push(this._overflowSizePage); |
| 796 |
|
| 797 |
// Request the model to be cleared to refresh all texture pages. |
| 798 |
this._requestClearModel = true; |
| 799 |
this._onAddTextureAtlasCanvas.fire(this._overflowSizePage.canvas); |
| 800 |
} |
| 801 |
activePage = this._overflowSizePage; |
| 802 |
activeRow = this._overflowSizePage.currentRow; |
| 803 |
// Move to next row if necessary |
| 804 |
if (activeRow.x + rasterizedGlyph.size.x >= activePage.canvas.width) { |
| 805 |
activeRow.x = 0; |
| 806 |
activeRow.y += activeRow.height; |
| 807 |
activeRow.height = 0; |
| 808 |
} |
| 809 |
break; |
| 810 |
} |
| 811 |
|
| 812 |
// Create a new page if too much vertical space would be wasted or there is not enough room |
| 813 |
// left in the page. The previous active row will become fixed in the process as it now has a |
| 814 |
// fixed height |
| 815 |
if (activeRow.y + rasterizedGlyph.size.y >= activePage.canvas.height || activeRow.height > rasterizedGlyph.size.y + Constants.ROW_PIXEL_THRESHOLD) { |
| 816 |
// Create the new fixed height row, creating a new page if there isn't enough room on the |
| 817 |
// current page |
| 818 |
let wasPageAndRowFound = false; |
| 819 |
if (activePage.currentRow.y + activePage.currentRow.height + rasterizedGlyph.size.y >= activePage.canvas.height) { |
| 820 |
// Find the first page with room to create the new row on |
| 821 |
let candidatePage: AtlasPage | undefined; |
| 822 |
|
| 823 |
for (const p of this._activePages) { |
| 824 |
if (p.currentRow.y + p.currentRow.height + rasterizedGlyph.size.y < p.canvas.height) { |
| 825 |
candidatePage = p; |
| 826 |
break; |
| 827 |
} |
| 828 |
} |
| 829 |
if (candidatePage) { |
| 830 |
activePage = candidatePage; |
| 831 |
} else { |
| 832 |
// Before creating a new atlas page that would trigger a page merge, check if the |
| 833 |
// current active row is sufficient when ignoring the ROW_PIXEL_THRESHOLD. This will |
| 834 |
// improve texture utilization by using the available space before the page is merged |
| 835 |
// and becomes static. |
| 836 |
if ( |
| 837 |
TextureAtlas.maxAtlasPages && |
| 838 |
this._pages.length >= TextureAtlas.maxAtlasPages && |
| 839 |
activeRow.y + rasterizedGlyph.size.y <= activePage.canvas.height && |
| 840 |
activeRow.height >= rasterizedGlyph.size.y && |
| 841 |
activeRow.x + rasterizedGlyph.size.x <= activePage.canvas.width |
| 842 |
) { |
| 843 |
// activePage and activeRow is already valid |
| 844 |
wasPageAndRowFound = true; |
| 845 |
} else { |
| 846 |
// Create a new page if there is no room |
| 847 |
const newPage = this._createNewPage(); |
| 848 |
activePage = newPage; |
| 849 |
activeRow = newPage.currentRow; |
| 850 |
activeRow.height = rasterizedGlyph.size.y; |
| 851 |
wasPageAndRowFound = true; |
| 852 |
} |
| 853 |
} |
| 854 |
} |
| 855 |
if (!wasPageAndRowFound) { |
| 856 |
// Fix the current row as the new row is being added below |
| 857 |
if (activePage.currentRow.height > 0) { |
| 858 |
activePage.fixedRows.push(activePage.currentRow); |
| 859 |
} |
| 860 |
activeRow = { |
| 861 |
x: 0, |
| 862 |
y: activePage.currentRow.y + activePage.currentRow.height, |
| 863 |
height: rasterizedGlyph.size.y |
| 864 |
}; |
| 865 |
activePage.fixedRows.push(activeRow); |
| 866 |
|
| 867 |
// Create the new current row below the new fixed height row |
| 868 |
activePage.currentRow = { |
| 869 |
x: 0, |
| 870 |
y: activeRow.y + activeRow.height, |
| 871 |
height: 0 |
| 872 |
}; |
| 873 |
} |
| 874 |
// TODO: Remove pages from _activePages when all rows are filled |
| 875 |
} |
| 876 |
|
| 877 |
// Exit the loop if there is enough room in the row |
| 878 |
if (activeRow.x + rasterizedGlyph.size.x <= activePage.canvas.width) { |
| 879 |
break; |
| 880 |
} |
| 881 |
|
| 882 |
// If there is not enough room in the current row, finish it and try again |
| 883 |
if (activeRow === activePage.currentRow) { |
| 884 |
activeRow.x = 0; |
| 885 |
activeRow.y += activeRow.height; |
| 886 |
activeRow.height = 0; |
| 887 |
} else { |
| 888 |
activePage.fixedRows.splice(activePage.fixedRows.indexOf(activeRow), 1); |
| 889 |
} |
| 890 |
} |
| 891 |
|
| 892 |
// Record texture position |
| 893 |
rasterizedGlyph.texturePage = this._pages.indexOf(activePage); |
| 894 |
rasterizedGlyph.texturePosition.x = activeRow.x; |
| 895 |
rasterizedGlyph.texturePosition.y = activeRow.y; |
| 896 |
rasterizedGlyph.texturePositionClipSpace.x = activeRow.x / activePage.canvas.width; |
| 897 |
rasterizedGlyph.texturePositionClipSpace.y = activeRow.y / activePage.canvas.height; |
| 898 |
|
| 899 |
// Fix the clipspace position as pages may be of differing size |
| 900 |
rasterizedGlyph.sizeClipSpace.x /= activePage.canvas.width; |
| 901 |
rasterizedGlyph.sizeClipSpace.y /= activePage.canvas.height; |
| 902 |
|
| 903 |
// Update atlas current row, for fixed rows the glyph height will never be larger than the row |
| 904 |
// height |
| 905 |
activeRow.height = Math.max(activeRow.height, rasterizedGlyph.size.y); |
| 906 |
activeRow.x += rasterizedGlyph.size.x; |
| 907 |
|
| 908 |
// putImageData doesn't do any blending, so it will overwrite any existing cache entry for us |
| 909 |
activePage.ctx.putImageData( |
| 910 |
imageData, |
| 911 |
rasterizedGlyph.texturePosition.x - this._workBoundingBox.left, |
| 912 |
rasterizedGlyph.texturePosition.y - this._workBoundingBox.top, |
| 913 |
this._workBoundingBox.left, |
| 914 |
this._workBoundingBox.top, |
| 915 |
rasterizedGlyph.size.x, |
| 916 |
rasterizedGlyph.size.y |
| 917 |
); |
| 918 |
activePage.addGlyph(rasterizedGlyph); |
| 919 |
activePage.version++; |
| 920 |
|
| 921 |
return rasterizedGlyph; |
| 922 |
} |
| 923 |
|
| 924 |
/** |
| 925 |
* Given an ImageData object, find the bounding box of the non-transparent |
| 926 |
* portion of the texture and return an IRasterizedGlyph with these |
| 927 |
* dimensions. |
| 928 |
* @param imageData The image data to read. |
| 929 |
* @param boundingBox An IBoundingBox to put the clipped bounding box values. |
| 930 |
*/ |
| 931 |
private _findGlyphBoundingBox(imageData: ImageData, boundingBox: IBoundingBox, allowedWidth: number, restrictedGlyph: boolean, customGlyph: boolean, padding: number): IRasterizedGlyph { |
| 932 |
boundingBox.top = 0; |
| 933 |
const height = restrictedGlyph ? this._config.deviceCellHeight : this._tmpCanvas.height; |
| 934 |
const width = restrictedGlyph ? this._config.deviceCellWidth : allowedWidth; |
| 935 |
let found = false; |
| 936 |
for (let y = 0; y < height; y++) { |
| 937 |
for (let x = 0; x < width; x++) { |
| 938 |
const alphaOffset = y * this._tmpCanvas.width * 4 + x * 4 + 3; |
| 939 |
if (imageData.data[alphaOffset] !== 0) { |
| 940 |
boundingBox.top = y; |
| 941 |
found = true; |
| 942 |
break; |
| 943 |
} |
| 944 |
} |
| 945 |
if (found) { |
| 946 |
break; |
| 947 |
} |
| 948 |
} |
| 949 |
boundingBox.left = 0; |
| 950 |
found = false; |
| 951 |
for (let x = 0; x < padding + width; x++) { |
| 952 |
for (let y = 0; y < height; y++) { |
| 953 |
const alphaOffset = y * this._tmpCanvas.width * 4 + x * 4 + 3; |
| 954 |
if (imageData.data[alphaOffset] !== 0) { |
| 955 |
boundingBox.left = x; |
| 956 |
found = true; |
| 957 |
break; |
| 958 |
} |
| 959 |
} |
| 960 |
if (found) { |
| 961 |
break; |
| 962 |
} |
| 963 |
} |
| 964 |
boundingBox.right = width; |
| 965 |
found = false; |
| 966 |
for (let x = padding + width - 1; x >= padding; x--) { |
| 967 |
for (let y = 0; y < height; y++) { |
| 968 |
const alphaOffset = y * this._tmpCanvas.width * 4 + x * 4 + 3; |
| 969 |
if (imageData.data[alphaOffset] !== 0) { |
| 970 |
boundingBox.right = x; |
| 971 |
found = true; |
| 972 |
break; |
| 973 |
} |
| 974 |
} |
| 975 |
if (found) { |
| 976 |
break; |
| 977 |
} |
| 978 |
} |
| 979 |
boundingBox.bottom = height; |
| 980 |
found = false; |
| 981 |
for (let y = height - 1; y >= 0; y--) { |
| 982 |
for (let x = 0; x < width; x++) { |
| 983 |
const alphaOffset = y * this._tmpCanvas.width * 4 + x * 4 + 3; |
| 984 |
if (imageData.data[alphaOffset] !== 0) { |
| 985 |
boundingBox.bottom = y; |
| 986 |
found = true; |
| 987 |
break; |
| 988 |
} |
| 989 |
} |
| 990 |
if (found) { |
| 991 |
break; |
| 992 |
} |
| 993 |
} |
| 994 |
return { |
| 995 |
texturePage: 0, |
| 996 |
texturePosition: { x: 0, y: 0 }, |
| 997 |
texturePositionClipSpace: { x: 0, y: 0 }, |
| 998 |
size: { |
| 999 |
x: boundingBox.right - boundingBox.left + 1, |
| 1000 |
y: boundingBox.bottom - boundingBox.top + 1 |
| 1001 |
}, |
| 1002 |
sizeClipSpace: { |
| 1003 |
x: (boundingBox.right - boundingBox.left + 1), |
| 1004 |
y: (boundingBox.bottom - boundingBox.top + 1) |
| 1005 |
}, |
| 1006 |
offset: { |
| 1007 |
x: -boundingBox.left + padding + ((restrictedGlyph || customGlyph) ? Math.floor((this._config.deviceCellWidth - this._config.deviceCharWidth) / 2) : 0), |
| 1008 |
y: -boundingBox.top + padding + ((restrictedGlyph || customGlyph) ? this._config.lineHeight === 1 ? 0 : Math.round((this._config.deviceCellHeight - this._config.deviceCharHeight) / 2) : 0) |
| 1009 |
} |
| 1010 |
}; |
| 1011 |
} |
| 1012 |
} |
| 1013 |
|
| 1014 |
class AtlasPage { |
| 1015 |
public readonly canvas: HTMLCanvasElement; |
| 1016 |
public readonly ctx: CanvasRenderingContext2D; |
| 1017 |
|
| 1018 |
private _usedPixels: number = 0; |
| 1019 |
public get percentageUsed(): number { return this._usedPixels / (this.canvas.width * this.canvas.height); } |
| 1020 |
|
| 1021 |
private readonly _glyphs: IRasterizedGlyph[] = []; |
| 1022 |
public get glyphs(): ReadonlyArray<IRasterizedGlyph> { return this._glyphs; } |
| 1023 |
public addGlyph(glyph: IRasterizedGlyph): void { |
| 1024 |
this._glyphs.push(glyph); |
| 1025 |
this._usedPixels += glyph.size.x * glyph.size.y; |
| 1026 |
} |
| 1027 |
|
| 1028 |
/** |
| 1029 |
* Used to check whether the canvas of the atlas page has changed. |
| 1030 |
*/ |
| 1031 |
public version = 0; |
| 1032 |
|
| 1033 |
// Texture atlas current positioning data. The texture packing strategy used is to fill from |
| 1034 |
// left-to-right and top-to-bottom. When the glyph being written is less than half of the current |
| 1035 |
// row's height, the following happens: |
| 1036 |
// |
| 1037 |
// - The current row becomes the fixed height row A |
| 1038 |
// - A new fixed height row B the exact size of the glyph is created below the current row |
| 1039 |
// - A new dynamic height current row is created below B |
| 1040 |
// |
| 1041 |
// This strategy does a good job preventing space being wasted for very short glyphs such as |
| 1042 |
// underscores, hyphens etc. or those with underlines rendered. |
| 1043 |
public currentRow: ICharAtlasActiveRow = { |
| 1044 |
x: 0, |
| 1045 |
y: 0, |
| 1046 |
height: 0 |
| 1047 |
}; |
| 1048 |
public readonly fixedRows: ICharAtlasActiveRow[] = []; |
| 1049 |
|
| 1050 |
constructor( |
| 1051 |
document: Document, |
| 1052 |
size: number, |
| 1053 |
sourcePages?: AtlasPage[] |
| 1054 |
) { |
| 1055 |
if (sourcePages) { |
| 1056 |
for (const p of sourcePages) { |
| 1057 |
this._glyphs.push(...p.glyphs); |
| 1058 |
this._usedPixels += p._usedPixels; |
| 1059 |
} |
| 1060 |
} |
| 1061 |
this.canvas = createCanvas(document, size, size); |
| 1062 |
// The canvas needs alpha because we use clearColor to convert the background color to alpha. |
| 1063 |
// It might also contain some characters with transparent backgrounds if allowTransparency is |
| 1064 |
// set. |
| 1065 |
this.ctx = throwIfFalsy(this.canvas.getContext('2d', { alpha: true })); |
| 1066 |
} |
| 1067 |
|
| 1068 |
public clear(): void { |
| 1069 |
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); |
| 1070 |
this.currentRow.x = 0; |
| 1071 |
this.currentRow.y = 0; |
| 1072 |
this.currentRow.height = 0; |
| 1073 |
this.fixedRows.length = 0; |
| 1074 |
this.version++; |
| 1075 |
} |
| 1076 |
} |
| 1077 |
|
| 1078 |
/** |
| 1079 |
* Makes a particular rgb color and colors that are nearly the same in an ImageData completely |
| 1080 |
* transparent. |
| 1081 |
* @returns True if the result is "empty", meaning all pixels are fully transparent. |
| 1082 |
*/ |
| 1083 |
function clearColor(imageData: ImageData, bg: IColor, fg: IColor, enableThresholdCheck: boolean): boolean { |
| 1084 |
// Get color channels |
| 1085 |
const r = bg.rgba >>> 24; |
| 1086 |
const g = bg.rgba >>> 16 & 0xFF; |
| 1087 |
const b = bg.rgba >>> 8 & 0xFF; |
| 1088 |
const fgR = fg.rgba >>> 24; |
| 1089 |
const fgG = fg.rgba >>> 16 & 0xFF; |
| 1090 |
const fgB = fg.rgba >>> 8 & 0xFF; |
| 1091 |
|
| 1092 |
// Calculate a threshold that when below a color will be treated as transpart when the sum of |
| 1093 |
// channel value differs. This helps improve rendering when glyphs overlap with others. This |
| 1094 |
// threshold is calculated relative to the difference between the background and foreground to |
| 1095 |
// ensure important details of the glyph are always shown, even when the contrast ratio is low. |
| 1096 |
// The number 12 is largely arbitrary to ensure the pixels that escape the cell in the test case |
| 1097 |
// were covered (fg=#8ae234, bg=#c4a000). |
| 1098 |
const threshold = Math.floor((Math.abs(r - fgR) + Math.abs(g - fgG) + Math.abs(b - fgB)) / 12); |
| 1099 |
|
| 1100 |
// Set alpha channel of relevent pixels to 0 |
| 1101 |
let isEmpty = true; |
| 1102 |
for (let offset = 0; offset < imageData.data.length; offset += 4) { |
| 1103 |
// Check exact match |
| 1104 |
if (imageData.data[offset] === r && |
| 1105 |
imageData.data[offset + 1] === g && |
| 1106 |
imageData.data[offset + 2] === b) { |
| 1107 |
imageData.data[offset + 3] = 0; |
| 1108 |
} else { |
| 1109 |
// Check the threshold based difference |
| 1110 |
if (enableThresholdCheck && |
| 1111 |
(Math.abs(imageData.data[offset] - r) + |
| 1112 |
Math.abs(imageData.data[offset + 1] - g) + |
| 1113 |
Math.abs(imageData.data[offset + 2] - b)) < threshold) { |
| 1114 |
imageData.data[offset + 3] = 0; |
| 1115 |
} else { |
| 1116 |
isEmpty = false; |
| 1117 |
} |
| 1118 |
} |
| 1119 |
} |
| 1120 |
|
| 1121 |
return isEmpty; |
| 1122 |
} |
| 1123 |
|
| 1124 |
function checkCompletelyTransparent(imageData: ImageData): boolean { |
| 1125 |
for (let offset = 0; offset < imageData.data.length; offset += 4) { |
| 1126 |
if (imageData.data[offset + 3] > 0) { |
| 1127 |
return false; |
| 1128 |
} |
| 1129 |
} |
| 1130 |
return true; |
| 1131 |
} |
| 1132 |
|
| 1133 |
function createCanvas(document: Document, width: number, height: number): HTMLCanvasElement { |
| 1134 |
const canvas = document.createElement('canvas'); |
| 1135 |
canvas.width = width; |
| 1136 |
canvas.height = height; |
| 1137 |
return canvas; |
| 1138 |
} |