- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344
- 345
- 346
- 347
- 348
- 349
- 350
- 351
- 352
- 353
- 354
- 355
- 356
- 357
- 358
- 359
- 360
- 361
- 362
- 363
- 364
- 365
- 366
- 367
- 368
- 369
- 370
- 371
- 372
- 373
- 374
- 375
- 376
- 377
- 378
- 379
- 380
- 381
- 382
- 383
- 384
- 385
- 386
- 387
- 388
- 389
- 390
- 391
- 392
- 393
- 394
- 395
- 396
- 397
- 398
- 399
- 400
- 401
- 402
- 403
- 404
- 405
- 406
- 407
- 408
- 409
- 410
- 411
- 412
- 413
- 414
- 415
- 416
- 417
- 418
- 419
- 420
- 421
- 422
- 423
- 424
- 425
- 426
- 427
- 428
- 429
- 430
- 431
- 432
- 433
- 434
- 435
- 436
- 437
- 438
- 439
- 440
- 441
- 442
- 443
- 444
- 445
- 446
- 447
- 448
- 449
- 450
- 451
- 452
- 453
- 454
- 455
- 456
- 457
- 458
- 459
- 460
- 461
- 462
- 463
- 464
- 465
import Color from "./../math/color.js";
import Matrix3d from "./../math/matrix3.js";
import { createCanvas } from "./video.js";
import * as event from "./../system/event.js";
import { platform } from "../system/device.js";
import { setPrefixed } from "./../utils/agent.js";
import Path2D from "./../geometries/path2d.js";
import Vector2d from "../math/vector2.js";
/**
* @classdesc
* a base renderer object
*/
export default class Renderer {
/**
* @param {Application.Settings} [options] - optional parameters for the renderer
*/
constructor(options) {
/**
* The given constructor options
* @public
* @type {object}
*/
this.settings = options;
/**
* the requested video size ratio
* @public
* @type {number}
*/
this.designRatio = this.settings.width / this.settings.height;
/**
* the scaling ratio to be applied to the main canvas
* @type {Vector2d}
* @default <1,1>
*/
this.scaleRatio = new Vector2d(this.settings.scale, this.settings.scale);
/**
* true if the current rendering context is valid
* @default true
* @type {boolean}
*/
this.isContextValid = true;
/**
* the default method to sort object ("sorting", "z-buffer")
* @type {string}
* @default "sorting"
*/
this.depthTest = "sorting";
/**
* The Path2D instance used by the renderer to draw primitives
* @type {Path2D}
*/
this.path2D = new Path2D();
/**
* The renderer type : Canvas, WebGL, etc...
* (override this property with a specific value when implementing a custom renderer)
* @type {string}
*/
this.type = "Generic";
/**
* @ignore
*/
this.currentScissor = new Int32Array([ 0, 0, this.settings.width, this.settings.height ]);
/**
* @ignore
*/
this.maskLevel = 0;
/**
* @ignore
*/
this.currentBlendMode = "none";
// create the main screen canvas
if (platform.ejecta === true) {
// a main canvas is already automatically created by Ejecta
this.canvas = globalThis.document.getElementById("canvas");
} else if (typeof globalThis.canvas !== "undefined") {
// a global canvas is available, e.g. webapp adapter for wechat
this.canvas = globalThis.canvas;
} else if (typeof this.settings.canvas !== "undefined") {
this.canvas = this.settings.canvas;
} else {
this.canvas = createCanvas(this.settings.width, this.settings.height);
}
// global color
this.currentColor = new Color(0, 0, 0, 1.0);
// global tint color
this.currentTint = new Color(255, 255, 255, 1.0);
// the projectionMatrix (set through setProjection)
this.projectionMatrix = new Matrix3d();
// default uvOffset
this.uvOffset = 0;
}
/**
* return the height of the canvas which this renderer draws to
* @returns {number} height of the system Canvas
*/
get height() {
return this.getCanvas().height;
}
set height(value) {
this.resize(this.width, value);
}
/**
* return the width of the canvas which this renderer draws to
* @returns {number} width of the system Canvas
*/
get width() {
return this.getCanvas().width;
}
set width(value) {
this.resize(value, this.height);
}
/**
* prepare the framebuffer for drawing a new frame
*/
clear() {}
/**
* render the main framebuffer on screen
*/
flush() {}
/**
* Reset context state
*/
reset() {
this.resetTransform();
this.setBlendMode(this.settings.blendMode);
this.setColor("#000000");
this.clearTint();
this.cache.clear();
this.currentScissor[0] = 0;
this.currentScissor[1] = 0;
this.currentScissor[2] = this.width;
this.currentScissor[3] = this.height;
this.clearMask();
}
/**
* return a reference to the canvas which this renderer draws to
* @returns {HTMLCanvasElement}
*/
getCanvas() {
return this.canvas;
}
/**
* return a reference to this renderer canvas corresponding Context
* @returns {CanvasRenderingContext2D|WebGLRenderingContext}
*/
getContext() {
return this.context;
}
/**
* returns the current blend mode for this renderer
* @returns {string} blend mode
*/
getBlendMode() {
return this.currentBlendMode;
}
/**
* Returns the 2D Context object of the given Canvas<br>
* Also configures anti-aliasing and blend modes based on constructor options.
* @param {HTMLCanvasElement} canvas
* @param {boolean} [transparent=true] - use false to disable transparency
* @returns {CanvasRenderingContext2D}
*/
getContext2d(canvas, transparent) {
if (typeof canvas === "undefined" || canvas === null) {
throw new Error(
"You must pass a canvas element in order to create " +
"a 2d context"
);
}
if (typeof canvas.getContext === "undefined") {
throw new Error(
"Your browser does not support HTML5 canvas."
);
}
if (typeof transparent !== "boolean") {
transparent = true;
}
let _context = canvas.getContext("2d", {
"alpha" : transparent
});
if (!_context.canvas) {
_context.canvas = canvas;
}
this.setAntiAlias(_context, this.settings.antiAlias);
return _context;
}
/**
* get the current fill & stroke style color.
* @returns {Color} current global color
*/
getColor() {
return this.currentColor;
}
/**
* return the current global alpha
* @returns {number}
*/
globalAlpha() {
return this.currentColor.glArray[3];
}
/**
* check if the given rect or bounds overlaps with the renderer screen coordinates
* @param {Rect|Bounds} bounds
* @returns {boolean} true if overlaps
*/
overlaps(bounds) {
return (
bounds.left <= this.width && bounds.right >= 0 &&
bounds.top <= this.height && bounds.bottom >= 0
);
}
/**
* resizes the system canvas
* @param {number} width - new width of the canvas
* @param {number} height - new height of the canvas
*/
resize(width, height) {
let canvas = this.getCanvas();
if (width !== canvas.width || height !== canvas.height) {
canvas.width = width;
canvas.height = height;
this.currentScissor[0] = 0;
this.currentScissor[1] = 0;
this.currentScissor[2] = width;
this.currentScissor[3] = height;
// publish the corresponding event
event.emit(event.CANVAS_ONRESIZE, width, height);
}
}
/**
* enable/disable image smoothing (scaling interpolation) for the given context
* @param {CanvasRenderingContext2D} context
* @param {boolean} [enable=false]
*/
setAntiAlias(context, enable) {
let canvas = context.canvas;
// enable/disable antialis on the given Context2d object
setPrefixed("imageSmoothingEnabled", enable === true, context);
// set antialias CSS property on the main canvas
if (enable !== true) {
// https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering
canvas.style["image-rendering"] = "optimizeSpeed"; // legal fallback
canvas.style["image-rendering"] = "-moz-crisp-edges"; // Firefox
canvas.style["image-rendering"] = "-o-crisp-edges"; // Opera
canvas.style["image-rendering"] = "-webkit-optimize-contrast"; // Safari
canvas.style["image-rendering"] = "optimize-contrast"; // CSS 3
canvas.style["image-rendering"] = "crisp-edges"; // CSS 4
canvas.style["image-rendering"] = "pixelated"; // CSS 4
canvas.style.msInterpolationMode = "nearest-neighbor"; // IE8+
} else {
canvas.style["image-rendering"] = "auto";
}
}
/**
* set/change the current projection matrix (WebGL only)
* @param {Matrix3d} matrix
*/
setProjection(matrix) {
this.projectionMatrix.copy(matrix);
}
/**
* stroke the given shape
* @param {Rect|RoundRect|Polygon|Line|Ellipse} shape - a shape object to stroke
* @param {boolean} [fill=false] - fill the shape with the current color if true
*/
stroke(shape, fill) {
switch (shape.type) {
// RoundRect
case "RoundRect":
this.strokeRoundRect(shape.left, shape.top, shape.width, shape.height, shape.radius, fill);
break;
// Rect or Bounds
case "Rectangle":
case "Bounds":
this.strokeRect(shape.left, shape.top, shape.width, shape.height, fill);
break;
// Polygon or Line
case "Polygon":
case "Line":
this.strokePolygon(shape, fill);
break;
case "Ellipse":
this.strokeEllipse(shape.pos.x, shape.pos.y, shape.radiusV.x, shape.radiusV.y, fill);
break;
// Point
case "Point":
this.strokePoint(shape.x, shape.y);
break;
default:
throw new Error("Invalid geometry for fill/stroke");
}
}
/**
* fill the given shape
* @param {Rect|RoundRect|Polygon|Line|Ellipse} shape - a shape object to fill
*/
fill(shape) {
this.stroke(shape, true);
}
/**
* tint the given image or canvas using the given color
* @param {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas} src - the source image to be tinted
* @param {Color|string} color - the color that will be used to tint the image
* @param {string} [mode="multiply"] - the composition mode used to tint the image
* @returns {HTMLCanvasElement|OffscreenCanvas} a new canvas element representing the tinted image
*/
tint(src, color, mode) {
let canvas = createCanvas(src.width, src.height, true);
let context = this.getContext2d(canvas);
context.save();
context.fillStyle = color instanceof Color ? color.toRGB() : color;
context.fillRect(0, 0, src.width, src.height);
context.globalCompositeOperation = mode || "multiply";
context.drawImage(src, 0, 0);
context.globalCompositeOperation = "destination-atop";
context.drawImage(src, 0, 0);
context.restore();
return canvas;
}
/**
* A mask limits rendering elements to the shape and position of the given mask object.
* So, if the renderable is larger than the mask, only the intersecting part of the renderable will be visible.
* Mask are not preserved through renderer context save and restore.
* @param {Rect|RoundRect|Polygon|Line|Ellipse} [mask] - the shape defining the mask to be applied
* @param {boolean} [invert=false] - either the given shape should define what is visible (default) or the opposite
*/
// eslint-disable-next-line no-unused-vars
setMask(mask, invert = false) {}
/**
* disable (remove) the rendering mask set through setMask.
* @see Renderer#setMask
*/
clearMask() {}
/**
* set a coloring tint for sprite based renderables
* @param {Color} tint - the tint color
* @param {number} [alpha] - an alpha value to be applied to the tint
*/
setTint(tint, alpha = tint.alpha) {
// global tint color
this.currentTint.copy(tint);
this.currentTint.alpha *= alpha;
}
/**
* clear the rendering tint set through setTint.
* @see Renderer#setTint
*/
clearTint() {
// reset to default
this.currentTint.setFloat(1.0, 1.0, 1.0, 1.0);
}
/**
* creates a Blob object representing the last rendered frame
* @param {string} [type="image/png"] - A string indicating the image format
* @param {number} [quality] - A Number between 0 and 1 indicating the image quality to be used when creating images using file formats that support lossy compression (such as image/jpeg or image/webp). A user agent will use its default quality value if this option is not specified, or if the number is outside the allowed range.
* @returns {Promise} A Promise returning a Blob object representing the last rendered frame
* @example
* renderer.convertToBlob().then((blob) => console.log(blob));
*/
toBlob(type = "image/png", quality) {
return new Promise((resolve) => {
event.once(event.GAME_AFTER_DRAW, () => {
this.canvas.toBlob((blob) => {
resolve(blob);
}, type, quality);
});
});
}
/**
* creates an ImageBitmap object of the last frame rendered
* (not supported by standard Canvas)
* @param {string} [type="image/png"] - A string indicating the image format
* @param {number} [quality] - A Number between 0 and 1 indicating the image quality to be used when creating images using file formats that support lossy compression (such as image/jpeg or image/webp). A user agent will use its default quality value if this option is not specified, or if the number is outside the allowed range.
* @returns {Promise} A Promise returning an ImageBitmap.
* @example
* renderer.transferToImageBitmap().then((image) => console.log(image));
*/
toImageBitmap(type = "image/png", quality) {
return new Promise((resolve) => {
event.once(event.GAME_AFTER_DRAW, () => {
let image = new Image();
image.src = this.canvas.toDataURL(type, quality);
image.onload = () => {
createImageBitmap(image).then((bitmap) => resolve(bitmap));
};
});
});
}
/**
* returns a data URL containing a representation of the last frame rendered
* @param {string} [type="image/png"] - A string indicating the image format
* @param {number} [quality] - A Number between 0 and 1 indicating the image quality to be used when creating images using file formats that support lossy compression (such as image/jpeg or image/webp). A user agent will use its default quality value if this option is not specified, or if the number is outside the allowed range.
* @returns {Promise} A Promise returning a string containing the requested data URL.
* @example
* renderer.toDataURL().then((dataURL) => console.log(dataURL));
*/
toDataURL(type = "image/png", quality) {
return new Promise((resolve) => {
event.once(event.GAME_AFTER_DRAW, () => {
resolve(this.canvas.toDataURL(type, quality));
});
});
}
}