[SOLVED] Dynamic texture creation

Here is a script I just wrote for you:

var ServerTexture = pc.createScript('serverTexture');

ServerTexture.attributes.add('serverTextures', {
    type: 'json',
    array: true,
    schema: [{
        name: 'url',
        type: 'string'
    }, {
        name: 'material',
        type: 'asset',
        assetType: 'material'
    }, {
        name: 'materialProperty',
        type: 'number',
        enum: [
            { 'Diffuse Map': 0 },
            { 'Emissive Map': 1 }
        ]
    }]
});

// initialize code called once per entity
ServerTexture.prototype.initialize = function() {
    this.serverTextures.forEach(function (serverTexture) {
        var image = new Image();
        image.crossOrigin = 'anonymous'; // This is critical when loading image from a different domain

        image.onload = function () {
            var texture = new pc.Texture(this.app.graphicsDevice, {
                magFilter: pc.FILTER_LINEAR,
                minFilter: pc.FILTER_LINEAR
            });
            texture.setSource(image);

            var mapNames = [ 'diffuseMap', 'emissiveMap' ];
            var mapName = mapNames[serverTexture.materialProperty];
            var material = serverTexture.material.resource;
            material[mapName] = texture;
            material.update();
        }.bind(this);
        image.src = serverTexture.url;
    }, this);
};

Here’s that script working in the Editor:

I’m using it to load this image from GitHub:

(The URL is https://raw.githubusercontent.com/playcanvas/editor/master/images/editor.png)

3 Likes