Can Render Material Color in runtime to dynamically loaded model

Front page code

<script>
                                                        var model_name_var = "{{ $items->model }}";
                                                    </script>
                                                    <h4 id="model_name" >{{ $items->model }}</h4>
                                                    
                                                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
                                                <script>
                                                
                                                  
                                                  window.onmessage = function(event) {
                                                    if (event.data == 'app:ready') {
                                                        var app = document.getElementById('app');
                                                    	app.contentWindow.postMessage('https://network.daruldev.com/models/'+model_name_var, '*');
                                                        
                                                    }
                                                    
                                                  }
                                                  $( window ).on( "load", function() {
                                                        console.log( "window loaded" );
                                                    });
                                                    $('#model').on('change', function (e) {
                                                        var optionSelected = $("option:selected", this);
                                                        var valueSelected = this.value;
                                                        console.log(valueSelected);
                                                    });
                                                </script>
                                                
                                                <script>
                                                $(document).ready(function(){
                                                    
                                                  $("select").change(function(){
                                                    var optionSelected = $("option:selected", this);
                                                    var valueSelected = this.value;
                                                     $.ajax({
                                                        type: 'GET', //THIS NEEDS TO BE GET
                                                        url: '{{ url("get_model") }}/'+valueSelected,
                                                        dataType: 'json',
                                                        success: function (data) {
                                                            console.log(data.model);
                                                            $('#ifram_div').empty();
                                                            $('<iframe>', {
                                                               src: 'https://playcanv.as/e/p/IFMi4dqz/',
                                                               id:  'app',
                                                               width: '100%',
                                                               height: '700px'
                                                               }).appendTo('#ifram_div');
                                                            model_name_var = data.model;
                                                        },error:function(){ 
                                                             console.log(data);
                                                        }
                                                    });
                                                  });
                                                });
                                                </script>
                                                <div id='ifram_div'>
                                                    <iframe src="https://playcanv.as/e/p/IFMi4dqz/" width="100%" height="700px" id='app'></iframe>
                                                </div>

Playcanvas Code

!function(e, t) {
    "use strict";
    var s = {};
    "undefined" != typeof module ? module.exports = s : e.OBJ = s,
        s.Mesh = function(e) {
        for (var t = [], s = [], r = [], n = {
            verts: [],
            norms: [],
            textures: [],
            hashindices: {},
            indices: [],
            index: 0
        }, i = e.split("\n"), u = /^v\s/, h = /^vn\s/, f = /^vt\s/, o = /^f\s/, a = /\s+/, d = 0; d < i.length; d++) {
            var l = i[d].trim()
            , c = l.split(a);
            if (c.shift(),
                u.test(l))
                t.push.apply(t, c);
            else if (h.test(l))
                s.push.apply(s, c);
            else if (f.test(l))
                r.push.apply(r, c);
            else if (o.test(l))
                for (var p = !1, x = 0, v = c.length; x < v; x++) {
                    if (3 !== x || p || (x = 2,
                                         p = !0),
                        c[x]in n.hashindices)
                        n.indices.push(n.hashindices[c[x]]);
                    else {
                        var m = c[x].split("/");
                        n.verts.push(+t[3 * (m[0] - 1) + 0]),
                            n.verts.push(+t[3 * (m[0] - 1) + 1]),
                            n.verts.push(+t[3 * (m[0] - 1) + 2]),
                            r.length && (n.textures.push(+r[2 * (m[1] - 1) + 0]),
                                         n.textures.push(+r[2 * (m[1] - 1) + 1])),
                            n.norms.push(+s[3 * (m[2] - 1) + 0]),
                            n.norms.push(+s[3 * (m[2] - 1) + 1]),
                            n.norms.push(+s[3 * (m[2] - 1) + 2]),
                            n.hashindices[c[x]] = n.index,
                            n.indices.push(n.index),
                            n.index += 1
                    }
                    3 === x && p && n.indices.push(n.hashindices[c[0]])
                }
        }
        this.vertices = n.verts,
            this.vertexNormals = n.norms,
            this.textures = n.textures,
            this.indices = n.indices
    }
    ;
    var r = function() {
        var e = this;
        this.xmlhttp = new XMLHttpRequest,
            this.get = function(t, s) {
            e.xmlhttp.onreadystatechange = function() {
                4 === e.xmlhttp.readyState && s(e.xmlhttp.responseText, e.xmlhttp.status)
            }
                ,
                e.xmlhttp.open("GET", t, !0),
                e.xmlhttp.send()
        }
    };
    s.downloadMeshes = function(e, t, n) {
        var i = Object.keys(e).length
        , u = !1;
        for (var h in void 0 === n && (n = {}),
            e)
            e.hasOwnProperty(h) && (new r).get(e[h], function(e) {
                return function(r, h) {
                    if (200 === h ? n[e] = new s.Mesh(r) : (u = !0,
                                                            console.error('An error has occurred and the mesh "' + e + '" could not be downloaded.')),
                        0 === --i) {
                        if (u)
                            throw console.error("An error has occurred and one or meshes has not been downloaded. The execution of the script has terminated."),
                                "";
                        t(n)
                    }
                }
            }(h))
    }
    ;
    var n = function(e, t, s, r) {
        var n = e.createBuffer()
        , i = t === e.ARRAY_BUFFER ? Float32Array : Uint16Array;
        return e.bindBuffer(t, n),
            e.bufferData(t, new i(s), e.STATIC_DRAW),
            n.itemSize = r,
            n.numItems = s.length / r,
            n
    };
    s.initMeshBuffers = function(e, t) {
        t.normalBuffer = n(e, e.ARRAY_BUFFER, t.vertexNormals, 3),
            t.textureBuffer = n(e, e.ARRAY_BUFFER, t.textures, 2),
            t.vertexBuffer = n(e, e.ARRAY_BUFFER, t.vertices, 3),
            t.indexBuffer = n(e, e.ELEMENT_ARRAY_BUFFER, t.indices, 1)
    }
        ,
        s.deleteMeshBuffers = function(e, t) {
        e.deleteBuffer(t.normalBuffer),
            e.deleteBuffer(t.textureBuffer),
            e.deleteBuffer(t.vertexBuffer),
            e.deleteBuffer(t.indexBuffer)
    }
}(this);

// Tell the iframe parent when it is ready
(function() {
    var app = pc.Application.getApplication();
    app.once('postrender', function() {
        if (window.parent) {
            window.parent.postMessage('app:ready', '*');
        }    
    });
})();





// Script
var Obj = pc.createScript("obj");

 

Obj.attributes.add("Mymaterial", {
    type: "asset",
    assetType: "material"
});
var product;  
 

Obj.prototype.loadModel = function(e) {
    
    var t = new OBJ.Mesh(e)
    , s = {};
    if (t.vertexNormals && (s.normals = t.vertexNormals),
        t.textures && (s.uvs = t.textures),
        t.indices && (s.indices = t.indices),
        t.vertices && t.vertexNormals && t.textures && t.indices) {
        var a = pc.calculateTangents(t.vertices, t.vertexNormals, t.textures, t.indices);
        s.tangents = a
    }
    var r = pc.createMesh(this.app.graphicsDevice, t.vertices, s)
    , o = new pc.GraphNode
    , i = this.Mymaterial ? this.Mymaterial.resource : new pc.StandardMaterial
    , n = new pc.MeshInstance(o,r,i)
    , c = new pc.Model;
    c.graph = o,
        c.meshInstances = [n],
        this.entity.addComponent("model"),
        this.entity.model.model = c
        this.entity.model.meshInstances[0] = this.Mymaterial.resource; 
       
        product = this.entity;
        
        //var res = event.data.split(",");
        var Glossy = 100;
        var Opaci = 50/100;
        //var Opaci = parseInt(res[1])/100;
        var Color = 'F4CB01';
        var Metalness = 50/100;
        this.Mymaterial.resource.opacity = 0;
        //this.entity.model.meshInstances[0].material.shininess = Glossy;
        //this.entity.model.meshInstances[0].material.metalness = Metalness;
        //this.entity.model.meshInstances[0].material.diffuse.fromString(Color);
        this.Mymaterial.resource.update();

        // product.destroy();
}

Obj.prototype.initialize = function() {
    window.onmessage = function(event) {
        // console.log(event);
        //alert(event.data);
        if(event.data.substring(0, 4) == 'prod'){
            console.log(event.data.replace('prod',''));
            var e = new pc.Asset("obj","text",{
                url: event.data.replace('prod','')
            });
        }else{
            var e = new pc.Asset("obj","text",{
                url: event.data
            });   
        }
        
        var t = this;
        
        e.ready(function(e) {
            t.loadModel(e.resource)
        });
            if(event.data.substring(0, 4) == 'flip'){
                var flipX = Number(event.data.substring(5, 6));
                var flipY = Number(event.data.substring(17, 18));
                var flipZ = Number(event.data.substring(11, 12));
                product.setEulerAngles(90*flipX,90*flipY,90*flipZ);
                console.log(flipX+' '+flipY+' '+flipZ);
            }
            else if(event.data.substring(0, 4) == 'prod'){
                // var flipX = Number(event.data.substring(5, 6));
                // var flipY = Number(event.data.substring(17, 18));
                // var flipZ = Number(event.data.substring(11, 12));
                // product.setEulerAngles(90*flipX,90*flipY,90*flipZ);
                this.app.assets.add(e);
                this.app.assets.load(e)
                console.log(event.data);
            }else{
                this.app.assets.add(e);
                this.app.assets.load(e)
            }
    }.bind(this);
    
    
    // camera = this.entity.script.orbitCamera;
    // camera.focus(this.entity);
}

Obj.prototype.update = function(e) {}

Here i was trying to implement material into model !

Hi @Fahadi_Nadeem,

What are you trying to do, change the color on an existing material? What error are you getting?

From your last code expert you posted, I think a potential issue with fromString(). I think it requires the full hex code string in this format:

.fromString('#F4CB01');

https://developer.playcanvas.com/en/api/pc.Color.html#fromString

And make sure the material you are updating is the same used in that mesh instance. You can also do this:

this.entity.model.meshInstances[0].material.update();

Yes I want to change current material color opacity etc.

Color I assume you mean the diffuse color? Here is some sample code:

this.entity.model.meshInstances[0].material.opacity = 0.5;
this.entity.model.meshInstances[0].material.diffuse.fromString('#F4CB01');
this.entity.model.meshInstances[0].material.update();

TypeError: Cannot set property ‘opacity’ of undefined
Getting this error

Can you post a simple sample project to take a look? Since you posted a lot of code that is quite impossible to debug out of context.

https://playcanvas.com/project/712735/overview/obj-loader-3

I run your project and see this:

Can you provide some steps on how to reproduce your issue? Steps, actions to do etc.

login to
http://network.daruldev.com/
admin@admin.com
123456
then go to below link where i want to change color etc !
http://network.daruldev.com/Edit-product_variations/2

Ok, I did and I see a UI for what it seems like a product configurator:

Your issue is how to pass the value to Playcanvas? Are you able to use postMessage to send the selected color value?

If you do that, then you can use the code I posted above to change the color and opacity of the selected material. Posted again for reference:

this.entity.model.meshInstances[0].material.opacity = 0.5;
this.entity.model.meshInstances[0].material.diffuse.fromString('#F4CB01');
this.entity.model.meshInstances[0].material.update();

Yes But now i am implementing through on playcanvas to implement the color opacity first ! and then will communicate after that working !

Ok, then try the code above to implement it in Playcanvas. Here is an example based on your project:

var materialXAxis = this.app.assets.find('Mat_x_axiz').resource;

materialXAxis.opacity = 1.0;
materialXAxis.diffuse.fromString('#F4CB01');
materialXAxis.update();

This will change the color and opacity of the X axis material:

Getting this error

Well, that seems like an issue of communication between your two windows, not selecting the material.

Check my last answer above, on changing color/opacity of a material.

Will it change the product color etc, that you can see up their ?

Sure, if you select the right material and that material uses a diffuse color. Then it will.

You can see that here that we are implementing material on run time So how will i do the referencing for that ?

I don’t see any difference, if it’s a Playcanvas material just do the same:

var material = this.entity.model.meshInstances[0].material;

material.opacity = 1.0;
material.diffuse.fromString('#F4CB01');
material.update();
1 Like

Getting this error :
TypeError: Cannot set property ‘opacity’ of undefined