diff --git a/build/litegraph.js b/build/litegraph.js index b24625637..ee8de0f79 100644 --- a/build/litegraph.js +++ b/build/litegraph.js @@ -1,5 +1,3 @@ -//packer version - (function(global){ // ************************************************************* // LiteGraph CLASS ******* @@ -2655,7 +2653,7 @@ LGraphNode.prototype.computeSize = function( minHeight, out ) * Allows to pass * * @method addWidget -* @return {Float32Array[4]} the total size +* @return {Object} the created widget */ LGraphNode.prototype.addWidget = function( type, name, value, callback, options ) { @@ -4096,7 +4094,7 @@ LGraphCanvas.prototype.processMouseDown = function(e) { //double click node if( node.onDblClick) - node.onDblClick(e,[e.canvasX - node.pos[0], e.canvasY - node.pos[1]],graphcanvas); + node.onDblClick(e,[e.canvasX - node.pos[0], e.canvasY - node.pos[1]], this); this.processNodeDblClicked( node ); block_drag_node = true; } @@ -8004,11 +8002,14 @@ function ContextMenu( values, options ) function on_mouse_wheel(e) { var pos = parseInt( root.style.top ); - root.style.top = (pos + e.deltaY * 0.1).toFixed() + "px"; + root.style.top = (pos + e.deltaY * options.scroll_speed).toFixed() + "px"; e.preventDefault(); return true; } + if(!options.scroll_speed) + options.scroll_speed = 0.1; + root.addEventListener("wheel", on_mouse_wheel, true); root.addEventListener("mousewheel", on_mouse_wheel, true); @@ -8891,262 +8892,262 @@ LiteGraph.registerNodeType("basic/script", NodeScript ); })(this); -//event related nodes -(function(global){ -var LiteGraph = global.LiteGraph; - -//Show value inside the debug console -function LogEvent() -{ - this.size = [60,20]; - this.addInput("event", LiteGraph.ACTION); -} - -LogEvent.title = "Log Event"; -LogEvent.desc = "Log event in console"; - -LogEvent.prototype.onAction = function( action, param ) -{ - console.log( action, param ); -} - -LiteGraph.registerNodeType("events/log", LogEvent ); - - -//Sequencer for events -function Sequencer() -{ - this.addInput("", LiteGraph.ACTION); - this.addInput("", LiteGraph.ACTION); - this.addInput("", LiteGraph.ACTION); - this.addInput("", LiteGraph.ACTION); - this.addInput("", LiteGraph.ACTION); - this.addInput("", LiteGraph.ACTION); - this.addOutput("", LiteGraph.EVENT); - this.addOutput("", LiteGraph.EVENT); - this.addOutput("", LiteGraph.EVENT); - this.addOutput("", LiteGraph.EVENT); - this.addOutput("", LiteGraph.EVENT); - this.addOutput("", LiteGraph.EVENT); - this.size = [120,30]; - this.flags = { horizontal: true, render_box: false }; -} - -Sequencer.title = "Sequencer"; -Sequencer.desc = "Trigger events when an event arrives"; - -Sequencer.prototype.getTitle = function() { return ""; } - -Sequencer.prototype.onAction = function( action, param ) -{ - if(this.outputs) - for(var i = 0; i < this.outputs.length; ++i) - this.triggerSlot( i, param ); -} - -LiteGraph.registerNodeType("events/sequencer", Sequencer ); - -//Filter events -function FilterEvent() -{ - this.size = [60,20]; - this.addInput("event", LiteGraph.ACTION); - this.addOutput("event", LiteGraph.EVENT); - this.properties = { - equal_to: "", - has_property:"", - property_equal_to: "" - }; -} - -FilterEvent.title = "Filter Event"; -FilterEvent.desc = "Blocks events that do not match the filter"; - -FilterEvent.prototype.onAction = function( action, param ) -{ - if( param == null ) - return; - - if( this.properties.equal_to && this.properties.equal_to != param ) - return; - - if( this.properties.has_property ) - { - var prop = param[ this.properties.has_property ]; - if( prop == null ) - return; - - if( this.properties.property_equal_to && this.properties.property_equal_to != prop ) - return; - } - - this.triggerSlot(0,param); -} - -LiteGraph.registerNodeType("events/filter", FilterEvent ); - - -//Show value inside the debug console -function EventCounter() -{ - this.addInput("inc", LiteGraph.ACTION); - this.addInput("dec", LiteGraph.ACTION); - this.addInput("reset", LiteGraph.ACTION); - this.addOutput("change", LiteGraph.EVENT); - this.addOutput("num", "number"); - this.num = 0; -} - -EventCounter.title = "Counter"; -EventCounter.desc = "Counts events"; - -EventCounter.prototype.onAction = function(action, param) -{ - var v = this.num; - if(action == "inc") - this.num += 1; - else if(action == "dec") - this.num -= 1; - else if(action == "reset") - this.num = 0; - if(this.num != v) - this.trigger("change",this.num); -} - -EventCounter.prototype.onDrawBackground = function(ctx) -{ - if(this.flags.collapsed) - return; - ctx.fillStyle = "#AAA"; - ctx.font = "20px Arial"; - ctx.textAlign = "center"; - ctx.fillText( this.num, this.size[0] * 0.5, this.size[1] * 0.5 ); -} - - -EventCounter.prototype.onExecute = function() -{ - this.setOutputData(1,this.num); -} - -LiteGraph.registerNodeType("events/counter", EventCounter ); - -//Show value inside the debug console -function DelayEvent() -{ - this.size = [60,20]; - this.addProperty( "time", 1000 ); - this.addInput("event", LiteGraph.ACTION); - this.addOutput("on_time", LiteGraph.EVENT); - - this._pending = []; -} - -DelayEvent.title = "Delay"; -DelayEvent.desc = "Delays one event"; - -DelayEvent.prototype.onAction = function(action, param) -{ - this._pending.push([ this.properties.time, param ]); -} - -DelayEvent.prototype.onExecute = function() -{ - var dt = this.graph.elapsed_time * 1000; //in ms - - for(var i = 0; i < this._pending.length; ++i) - { - var action = this._pending[i]; - action[0] -= dt; - if( action[0] > 0 ) - continue; - - //remove - this._pending.splice(i,1); - --i; - - //trigger - this.trigger(null, action[1]); - } -} - -DelayEvent.prototype.onGetInputs = function() -{ - return [["event",LiteGraph.ACTION]]; -} - -LiteGraph.registerNodeType("events/delay", DelayEvent ); - - -//Show value inside the debug console -function TimerEvent() -{ - this.addProperty("interval", 1000); - this.addProperty("event", "tick"); - this.addOutput("on_tick", LiteGraph.EVENT); - this.time = 0; - this.last_interval = 1000; - this.triggered = false; -} - -TimerEvent.title = "Timer"; -TimerEvent.desc = "Sends an event every N milliseconds"; - -TimerEvent.prototype.onStart = function() -{ - this.time = 0; -} - -TimerEvent.prototype.getTitle = function() -{ - return "Timer: " + this.last_interval.toString() + "ms"; -} - -TimerEvent.on_color = "#AAA"; -TimerEvent.off_color = "#222"; - -TimerEvent.prototype.onDrawBackground = function() -{ - this.boxcolor = this.triggered ? TimerEvent.on_color : TimerEvent.off_color; - this.triggered = false; -} - -TimerEvent.prototype.onExecute = function() -{ - var dt = this.graph.elapsed_time * 1000; //in ms - - var trigger = this.time == 0; - - this.time += dt; - this.last_interval = Math.max(1, this.getInputOrProperty("interval") | 0); - - if( !trigger && ( this.time < this.last_interval || isNaN(this.last_interval)) ) - { - if( this.inputs && this.inputs.length > 1 && this.inputs[1] ) - this.setOutputData(1,false); - return; - } - - this.triggered = true; - this.time = this.time % this.last_interval; - this.trigger( "on_tick", this.properties.event ); - if( this.inputs && this.inputs.length > 1 && this.inputs[1] ) - this.setOutputData( 1, true ); -} - -TimerEvent.prototype.onGetInputs = function() -{ - return [["interval","number"]]; -} - -TimerEvent.prototype.onGetOutputs = function() -{ - return [["tick","boolean"]]; -} - -LiteGraph.registerNodeType("events/timer", TimerEvent ); - - +//event related nodes +(function(global){ +var LiteGraph = global.LiteGraph; + +//Show value inside the debug console +function LogEvent() +{ + this.size = [60,20]; + this.addInput("event", LiteGraph.ACTION); +} + +LogEvent.title = "Log Event"; +LogEvent.desc = "Log event in console"; + +LogEvent.prototype.onAction = function( action, param ) +{ + console.log( action, param ); +} + +LiteGraph.registerNodeType("events/log", LogEvent ); + + +//Sequencer for events +function Sequencer() +{ + this.addInput("", LiteGraph.ACTION); + this.addInput("", LiteGraph.ACTION); + this.addInput("", LiteGraph.ACTION); + this.addInput("", LiteGraph.ACTION); + this.addInput("", LiteGraph.ACTION); + this.addInput("", LiteGraph.ACTION); + this.addOutput("", LiteGraph.EVENT); + this.addOutput("", LiteGraph.EVENT); + this.addOutput("", LiteGraph.EVENT); + this.addOutput("", LiteGraph.EVENT); + this.addOutput("", LiteGraph.EVENT); + this.addOutput("", LiteGraph.EVENT); + this.size = [120,30]; + this.flags = { horizontal: true, render_box: false }; +} + +Sequencer.title = "Sequencer"; +Sequencer.desc = "Trigger events when an event arrives"; + +Sequencer.prototype.getTitle = function() { return ""; } + +Sequencer.prototype.onAction = function( action, param ) +{ + if(this.outputs) + for(var i = 0; i < this.outputs.length; ++i) + this.triggerSlot( i, param ); +} + +LiteGraph.registerNodeType("events/sequencer", Sequencer ); + +//Filter events +function FilterEvent() +{ + this.size = [60,20]; + this.addInput("event", LiteGraph.ACTION); + this.addOutput("event", LiteGraph.EVENT); + this.properties = { + equal_to: "", + has_property:"", + property_equal_to: "" + }; +} + +FilterEvent.title = "Filter Event"; +FilterEvent.desc = "Blocks events that do not match the filter"; + +FilterEvent.prototype.onAction = function( action, param ) +{ + if( param == null ) + return; + + if( this.properties.equal_to && this.properties.equal_to != param ) + return; + + if( this.properties.has_property ) + { + var prop = param[ this.properties.has_property ]; + if( prop == null ) + return; + + if( this.properties.property_equal_to && this.properties.property_equal_to != prop ) + return; + } + + this.triggerSlot(0,param); +} + +LiteGraph.registerNodeType("events/filter", FilterEvent ); + + +//Show value inside the debug console +function EventCounter() +{ + this.addInput("inc", LiteGraph.ACTION); + this.addInput("dec", LiteGraph.ACTION); + this.addInput("reset", LiteGraph.ACTION); + this.addOutput("change", LiteGraph.EVENT); + this.addOutput("num", "number"); + this.num = 0; +} + +EventCounter.title = "Counter"; +EventCounter.desc = "Counts events"; + +EventCounter.prototype.onAction = function(action, param) +{ + var v = this.num; + if(action == "inc") + this.num += 1; + else if(action == "dec") + this.num -= 1; + else if(action == "reset") + this.num = 0; + if(this.num != v) + this.trigger("change",this.num); +} + +EventCounter.prototype.onDrawBackground = function(ctx) +{ + if(this.flags.collapsed) + return; + ctx.fillStyle = "#AAA"; + ctx.font = "20px Arial"; + ctx.textAlign = "center"; + ctx.fillText( this.num, this.size[0] * 0.5, this.size[1] * 0.5 ); +} + + +EventCounter.prototype.onExecute = function() +{ + this.setOutputData(1,this.num); +} + +LiteGraph.registerNodeType("events/counter", EventCounter ); + +//Show value inside the debug console +function DelayEvent() +{ + this.size = [60,20]; + this.addProperty( "time", 1000 ); + this.addInput("event", LiteGraph.ACTION); + this.addOutput("on_time", LiteGraph.EVENT); + + this._pending = []; +} + +DelayEvent.title = "Delay"; +DelayEvent.desc = "Delays one event"; + +DelayEvent.prototype.onAction = function(action, param) +{ + this._pending.push([ this.properties.time, param ]); +} + +DelayEvent.prototype.onExecute = function() +{ + var dt = this.graph.elapsed_time * 1000; //in ms + + for(var i = 0; i < this._pending.length; ++i) + { + var action = this._pending[i]; + action[0] -= dt; + if( action[0] > 0 ) + continue; + + //remove + this._pending.splice(i,1); + --i; + + //trigger + this.trigger(null, action[1]); + } +} + +DelayEvent.prototype.onGetInputs = function() +{ + return [["event",LiteGraph.ACTION]]; +} + +LiteGraph.registerNodeType("events/delay", DelayEvent ); + + +//Show value inside the debug console +function TimerEvent() +{ + this.addProperty("interval", 1000); + this.addProperty("event", "tick"); + this.addOutput("on_tick", LiteGraph.EVENT); + this.time = 0; + this.last_interval = 1000; + this.triggered = false; +} + +TimerEvent.title = "Timer"; +TimerEvent.desc = "Sends an event every N milliseconds"; + +TimerEvent.prototype.onStart = function() +{ + this.time = 0; +} + +TimerEvent.prototype.getTitle = function() +{ + return "Timer: " + this.last_interval.toString() + "ms"; +} + +TimerEvent.on_color = "#AAA"; +TimerEvent.off_color = "#222"; + +TimerEvent.prototype.onDrawBackground = function() +{ + this.boxcolor = this.triggered ? TimerEvent.on_color : TimerEvent.off_color; + this.triggered = false; +} + +TimerEvent.prototype.onExecute = function() +{ + var dt = this.graph.elapsed_time * 1000; //in ms + + var trigger = this.time == 0; + + this.time += dt; + this.last_interval = Math.max(1, this.getInputOrProperty("interval") | 0); + + if( !trigger && ( this.time < this.last_interval || isNaN(this.last_interval)) ) + { + if( this.inputs && this.inputs.length > 1 && this.inputs[1] ) + this.setOutputData(1,false); + return; + } + + this.triggered = true; + this.time = this.time % this.last_interval; + this.trigger( "on_tick", this.properties.event ); + if( this.inputs && this.inputs.length > 1 && this.inputs[1] ) + this.setOutputData( 1, true ); +} + +TimerEvent.prototype.onGetInputs = function() +{ + return [["interval","number"]]; +} + +TimerEvent.prototype.onGetOutputs = function() +{ + return [["tick","boolean"]]; +} + +LiteGraph.registerNodeType("events/timer", TimerEvent ); + + })(this); //widgets (function(global){ @@ -9874,1334 +9875,1334 @@ var LiteGraph = global.LiteGraph; LiteGraph.registerNodeType("widget/panel", WidgetPanel ); })(this); -(function(global){ -var LiteGraph = global.LiteGraph; - -function GamepadInput() -{ - this.addOutput("left_x_axis","number"); - this.addOutput("left_y_axis","number"); - this.addOutput( "button_pressed", LiteGraph.EVENT ); - this.properties = { gamepad_index: 0, threshold: 0.1 }; - - this._left_axis = new Float32Array(2); - this._right_axis = new Float32Array(2); - this._triggers = new Float32Array(2); - this._previous_buttons = new Uint8Array(17); - this._current_buttons = new Uint8Array(17); -} - -GamepadInput.title = "Gamepad"; -GamepadInput.desc = "gets the input of the gamepad"; - -GamepadInput.zero = new Float32Array(2); -GamepadInput.buttons = ["a","b","x","y","lb","rb","lt","rt","back","start","ls","rs","home"]; - -GamepadInput.prototype.onExecute = function() -{ - //get gamepad - var gamepad = this.getGamepad(); - var threshold = this.properties.threshold || 0.0; - - if(gamepad) - { - this._left_axis[0] = Math.abs( gamepad.xbox.axes["lx"] ) > threshold ? gamepad.xbox.axes["lx"] : 0; - this._left_axis[1] = Math.abs( gamepad.xbox.axes["ly"] ) > threshold ? gamepad.xbox.axes["ly"] : 0; - this._right_axis[0] = Math.abs( gamepad.xbox.axes["rx"] ) > threshold ? gamepad.xbox.axes["rx"] : 0; - this._right_axis[1] = Math.abs( gamepad.xbox.axes["ry"] ) > threshold ? gamepad.xbox.axes["ry"] : 0; - this._triggers[0] = Math.abs( gamepad.xbox.axes["ltrigger"] ) > threshold ? gamepad.xbox.axes["ltrigger"] : 0; - this._triggers[1] = Math.abs( gamepad.xbox.axes["rtrigger"] ) > threshold ? gamepad.xbox.axes["rtrigger"] : 0; - } - - if(this.outputs) - { - for(var i = 0; i < this.outputs.length; i++) - { - var output = this.outputs[i]; - if(!output.links || !output.links.length) - continue; - var v = null; - - if(gamepad) - { - switch( output.name ) - { - case "left_axis": v = this._left_axis; break; - case "right_axis": v = this._right_axis; break; - case "left_x_axis": v = this._left_axis[0]; break; - case "left_y_axis": v = this._left_axis[1]; break; - case "right_x_axis": v = this._right_axis[0]; break; - case "right_y_axis": v = this._right_axis[1]; break; - case "trigger_left": v = this._triggers[0]; break; - case "trigger_right": v = this._triggers[1]; break; - case "a_button": v = gamepad.xbox.buttons["a"] ? 1 : 0; break; - case "b_button": v = gamepad.xbox.buttons["b"] ? 1 : 0; break; - case "x_button": v = gamepad.xbox.buttons["x"] ? 1 : 0; break; - case "y_button": v = gamepad.xbox.buttons["y"] ? 1 : 0; break; - case "lb_button": v = gamepad.xbox.buttons["lb"] ? 1 : 0; break; - case "rb_button": v = gamepad.xbox.buttons["rb"] ? 1 : 0; break; - case "ls_button": v = gamepad.xbox.buttons["ls"] ? 1 : 0; break; - case "rs_button": v = gamepad.xbox.buttons["rs"] ? 1 : 0; break; - case "start_button": v = gamepad.xbox.buttons["start"] ? 1 : 0; break; - case "back_button": v = gamepad.xbox.buttons["back"] ? 1 : 0; break; - case "button_pressed": - for(var j = 0; j < this._current_buttons.length; ++j) - { - if( this._current_buttons[j] && !this._previous_buttons[j] ) - this.triggerSlot( i, GamepadInput.buttons[j] ); - } - break; - default: break; - } - } - else - { - //if no gamepad is connected, output 0 - switch( output.name ) - { - case "button_pressed": break; - case "left_axis": - case "right_axis": - v = GamepadInput.zero; - break; - default: - v = 0; - } - } - this.setOutputData(i,v); - } - } -} - -GamepadInput.prototype.getGamepad = function() -{ - var getGamepads = navigator.getGamepads || navigator.webkitGetGamepads || navigator.mozGetGamepads; - if(!getGamepads) - return null; - var gamepads = getGamepads.call(navigator); - var gamepad = null; - - this._previous_buttons.set( this._current_buttons ); - - //pick the first connected - for(var i = this.properties.gamepad_index; i < 4; i++) - { - if (gamepads[i]) - { - gamepad = gamepads[i]; - - //xbox controller mapping - var xbox = this.xbox_mapping; - if(!xbox) - xbox = this.xbox_mapping = { axes:[], buttons:{}, hat: ""}; - - xbox.axes["lx"] = gamepad.axes[0]; - xbox.axes["ly"] = gamepad.axes[1]; - xbox.axes["rx"] = gamepad.axes[2]; - xbox.axes["ry"] = gamepad.axes[3]; - xbox.axes["ltrigger"] = gamepad.buttons[6].value; - xbox.axes["rtrigger"] = gamepad.buttons[7].value; - - for(var j = 0; j < gamepad.buttons.length; j++) - { - this._current_buttons[j] = gamepad.buttons[j].pressed; - - //mapping of XBOX - switch(j) //I use a switch to ensure that a player with another gamepad could play - { - case 0: xbox.buttons["a"] = gamepad.buttons[j].pressed; break; - case 1: xbox.buttons["b"] = gamepad.buttons[j].pressed; break; - case 2: xbox.buttons["x"] = gamepad.buttons[j].pressed; break; - case 3: xbox.buttons["y"] = gamepad.buttons[j].pressed; break; - case 4: xbox.buttons["lb"] = gamepad.buttons[j].pressed; break; - case 5: xbox.buttons["rb"] = gamepad.buttons[j].pressed; break; - case 6: xbox.buttons["lt"] = gamepad.buttons[j].pressed; break; - case 7: xbox.buttons["rt"] = gamepad.buttons[j].pressed; break; - case 8: xbox.buttons["back"] = gamepad.buttons[j].pressed; break; - case 9: xbox.buttons["start"] = gamepad.buttons[j].pressed; break; - case 10: xbox.buttons["ls"] = gamepad.buttons[j].pressed; break; - case 11: xbox.buttons["rs"] = gamepad.buttons[j].pressed; break; - case 12: if( gamepad.buttons[j].pressed) xbox.hat += "up"; break; - case 13: if( gamepad.buttons[j].pressed) xbox.hat += "down"; break; - case 14: if( gamepad.buttons[j].pressed) xbox.hat += "left"; break; - case 15: if( gamepad.buttons[j].pressed) xbox.hat += "right"; break; - case 16: xbox.buttons["home"] = gamepad.buttons[j].pressed; break; - default: - } - } - gamepad.xbox = xbox; - return gamepad; - } - } -} - -GamepadInput.prototype.onDrawBackground = function(ctx) -{ - if(this.flags.collapsed) - return; - - //render gamepad state? - var la = this._left_axis; - var ra = this._right_axis; - ctx.strokeStyle = "#88A"; - ctx.strokeRect( (la[0] + 1) * 0.5 * this.size[0] - 4, (la[1] + 1) * 0.5 * this.size[1] - 4, 8, 8 ); - ctx.strokeStyle = "#8A8"; - ctx.strokeRect( (ra[0] + 1) * 0.5 * this.size[0] - 4, (ra[1] + 1) * 0.5 * this.size[1] - 4, 8, 8 ); - var h = this.size[1] / this._current_buttons.length - ctx.fillStyle = "#AEB"; - for(var i = 0; i < this._current_buttons.length; ++i) - if(this._current_buttons[i]) - ctx.fillRect( 0, h * i, 6, h); -} - -GamepadInput.prototype.onGetOutputs = function() { - return [ - ["left_axis","vec2"], - ["right_axis","vec2"], - ["left_x_axis","number"], - ["left_y_axis","number"], - ["right_x_axis","number"], - ["right_y_axis","number"], - ["trigger_left","number"], - ["trigger_right","number"], - ["a_button","number"], - ["b_button","number"], - ["x_button","number"], - ["y_button","number"], - ["lb_button","number"], - ["rb_button","number"], - ["ls_button","number"], - ["rs_button","number"], - ["start","number"], - ["back","number"], - ["button_pressed", LiteGraph.EVENT] - ]; -} - -LiteGraph.registerNodeType("input/gamepad", GamepadInput ); - +(function(global){ +var LiteGraph = global.LiteGraph; + +function GamepadInput() +{ + this.addOutput("left_x_axis","number"); + this.addOutput("left_y_axis","number"); + this.addOutput( "button_pressed", LiteGraph.EVENT ); + this.properties = { gamepad_index: 0, threshold: 0.1 }; + + this._left_axis = new Float32Array(2); + this._right_axis = new Float32Array(2); + this._triggers = new Float32Array(2); + this._previous_buttons = new Uint8Array(17); + this._current_buttons = new Uint8Array(17); +} + +GamepadInput.title = "Gamepad"; +GamepadInput.desc = "gets the input of the gamepad"; + +GamepadInput.zero = new Float32Array(2); +GamepadInput.buttons = ["a","b","x","y","lb","rb","lt","rt","back","start","ls","rs","home"]; + +GamepadInput.prototype.onExecute = function() +{ + //get gamepad + var gamepad = this.getGamepad(); + var threshold = this.properties.threshold || 0.0; + + if(gamepad) + { + this._left_axis[0] = Math.abs( gamepad.xbox.axes["lx"] ) > threshold ? gamepad.xbox.axes["lx"] : 0; + this._left_axis[1] = Math.abs( gamepad.xbox.axes["ly"] ) > threshold ? gamepad.xbox.axes["ly"] : 0; + this._right_axis[0] = Math.abs( gamepad.xbox.axes["rx"] ) > threshold ? gamepad.xbox.axes["rx"] : 0; + this._right_axis[1] = Math.abs( gamepad.xbox.axes["ry"] ) > threshold ? gamepad.xbox.axes["ry"] : 0; + this._triggers[0] = Math.abs( gamepad.xbox.axes["ltrigger"] ) > threshold ? gamepad.xbox.axes["ltrigger"] : 0; + this._triggers[1] = Math.abs( gamepad.xbox.axes["rtrigger"] ) > threshold ? gamepad.xbox.axes["rtrigger"] : 0; + } + + if(this.outputs) + { + for(var i = 0; i < this.outputs.length; i++) + { + var output = this.outputs[i]; + if(!output.links || !output.links.length) + continue; + var v = null; + + if(gamepad) + { + switch( output.name ) + { + case "left_axis": v = this._left_axis; break; + case "right_axis": v = this._right_axis; break; + case "left_x_axis": v = this._left_axis[0]; break; + case "left_y_axis": v = this._left_axis[1]; break; + case "right_x_axis": v = this._right_axis[0]; break; + case "right_y_axis": v = this._right_axis[1]; break; + case "trigger_left": v = this._triggers[0]; break; + case "trigger_right": v = this._triggers[1]; break; + case "a_button": v = gamepad.xbox.buttons["a"] ? 1 : 0; break; + case "b_button": v = gamepad.xbox.buttons["b"] ? 1 : 0; break; + case "x_button": v = gamepad.xbox.buttons["x"] ? 1 : 0; break; + case "y_button": v = gamepad.xbox.buttons["y"] ? 1 : 0; break; + case "lb_button": v = gamepad.xbox.buttons["lb"] ? 1 : 0; break; + case "rb_button": v = gamepad.xbox.buttons["rb"] ? 1 : 0; break; + case "ls_button": v = gamepad.xbox.buttons["ls"] ? 1 : 0; break; + case "rs_button": v = gamepad.xbox.buttons["rs"] ? 1 : 0; break; + case "start_button": v = gamepad.xbox.buttons["start"] ? 1 : 0; break; + case "back_button": v = gamepad.xbox.buttons["back"] ? 1 : 0; break; + case "button_pressed": + for(var j = 0; j < this._current_buttons.length; ++j) + { + if( this._current_buttons[j] && !this._previous_buttons[j] ) + this.triggerSlot( i, GamepadInput.buttons[j] ); + } + break; + default: break; + } + } + else + { + //if no gamepad is connected, output 0 + switch( output.name ) + { + case "button_pressed": break; + case "left_axis": + case "right_axis": + v = GamepadInput.zero; + break; + default: + v = 0; + } + } + this.setOutputData(i,v); + } + } +} + +GamepadInput.prototype.getGamepad = function() +{ + var getGamepads = navigator.getGamepads || navigator.webkitGetGamepads || navigator.mozGetGamepads; + if(!getGamepads) + return null; + var gamepads = getGamepads.call(navigator); + var gamepad = null; + + this._previous_buttons.set( this._current_buttons ); + + //pick the first connected + for(var i = this.properties.gamepad_index; i < 4; i++) + { + if (gamepads[i]) + { + gamepad = gamepads[i]; + + //xbox controller mapping + var xbox = this.xbox_mapping; + if(!xbox) + xbox = this.xbox_mapping = { axes:[], buttons:{}, hat: ""}; + + xbox.axes["lx"] = gamepad.axes[0]; + xbox.axes["ly"] = gamepad.axes[1]; + xbox.axes["rx"] = gamepad.axes[2]; + xbox.axes["ry"] = gamepad.axes[3]; + xbox.axes["ltrigger"] = gamepad.buttons[6].value; + xbox.axes["rtrigger"] = gamepad.buttons[7].value; + + for(var j = 0; j < gamepad.buttons.length; j++) + { + this._current_buttons[j] = gamepad.buttons[j].pressed; + + //mapping of XBOX + switch(j) //I use a switch to ensure that a player with another gamepad could play + { + case 0: xbox.buttons["a"] = gamepad.buttons[j].pressed; break; + case 1: xbox.buttons["b"] = gamepad.buttons[j].pressed; break; + case 2: xbox.buttons["x"] = gamepad.buttons[j].pressed; break; + case 3: xbox.buttons["y"] = gamepad.buttons[j].pressed; break; + case 4: xbox.buttons["lb"] = gamepad.buttons[j].pressed; break; + case 5: xbox.buttons["rb"] = gamepad.buttons[j].pressed; break; + case 6: xbox.buttons["lt"] = gamepad.buttons[j].pressed; break; + case 7: xbox.buttons["rt"] = gamepad.buttons[j].pressed; break; + case 8: xbox.buttons["back"] = gamepad.buttons[j].pressed; break; + case 9: xbox.buttons["start"] = gamepad.buttons[j].pressed; break; + case 10: xbox.buttons["ls"] = gamepad.buttons[j].pressed; break; + case 11: xbox.buttons["rs"] = gamepad.buttons[j].pressed; break; + case 12: if( gamepad.buttons[j].pressed) xbox.hat += "up"; break; + case 13: if( gamepad.buttons[j].pressed) xbox.hat += "down"; break; + case 14: if( gamepad.buttons[j].pressed) xbox.hat += "left"; break; + case 15: if( gamepad.buttons[j].pressed) xbox.hat += "right"; break; + case 16: xbox.buttons["home"] = gamepad.buttons[j].pressed; break; + default: + } + } + gamepad.xbox = xbox; + return gamepad; + } + } +} + +GamepadInput.prototype.onDrawBackground = function(ctx) +{ + if(this.flags.collapsed) + return; + + //render gamepad state? + var la = this._left_axis; + var ra = this._right_axis; + ctx.strokeStyle = "#88A"; + ctx.strokeRect( (la[0] + 1) * 0.5 * this.size[0] - 4, (la[1] + 1) * 0.5 * this.size[1] - 4, 8, 8 ); + ctx.strokeStyle = "#8A8"; + ctx.strokeRect( (ra[0] + 1) * 0.5 * this.size[0] - 4, (ra[1] + 1) * 0.5 * this.size[1] - 4, 8, 8 ); + var h = this.size[1] / this._current_buttons.length + ctx.fillStyle = "#AEB"; + for(var i = 0; i < this._current_buttons.length; ++i) + if(this._current_buttons[i]) + ctx.fillRect( 0, h * i, 6, h); +} + +GamepadInput.prototype.onGetOutputs = function() { + return [ + ["left_axis","vec2"], + ["right_axis","vec2"], + ["left_x_axis","number"], + ["left_y_axis","number"], + ["right_x_axis","number"], + ["right_y_axis","number"], + ["trigger_left","number"], + ["trigger_right","number"], + ["a_button","number"], + ["b_button","number"], + ["x_button","number"], + ["y_button","number"], + ["lb_button","number"], + ["rb_button","number"], + ["ls_button","number"], + ["rs_button","number"], + ["start","number"], + ["back","number"], + ["button_pressed", LiteGraph.EVENT] + ]; +} + +LiteGraph.registerNodeType("input/gamepad", GamepadInput ); + })(this); -(function(global){ -var LiteGraph = global.LiteGraph; - -//Converter -function Converter() -{ - this.addInput("in","*"); - this.size = [60,20]; -} - -Converter.title = "Converter"; -Converter.desc = "type A to type B"; - -Converter.prototype.onExecute = function() -{ - var v = this.getInputData(0); - if(v == null) - return; - - if(this.outputs) - for(var i = 0; i < this.outputs.length; i++) - { - var output = this.outputs[i]; - if(!output.links || !output.links.length) - continue; - - var result = null; - switch( output.name ) - { - case "number": result = v.length ? v[0] : parseFloat(v); break; - case "vec2": - case "vec3": - case "vec4": - var result = null; - var count = 1; - switch(output.name) - { - case "vec2": count = 2; break; - case "vec3": count = 3; break; - case "vec4": count = 4; break; - } - - var result = new Float32Array( count ); - if( v.length ) - { - for(var j = 0; j < v.length && j < result.length; j++) - result[j] = v[j]; - } - else - result[0] = parseFloat(v); - break; - } - this.setOutputData(i, result); - } -} - -Converter.prototype.onGetOutputs = function() { - return [["number","number"],["vec2","vec2"],["vec3","vec3"],["vec4","vec4"]]; -} - -LiteGraph.registerNodeType("math/converter", Converter ); - - -//Bypass -function Bypass() -{ - this.addInput("in"); - this.addOutput("out"); - this.size = [60,20]; -} - -Bypass.title = "Bypass"; -Bypass.desc = "removes the type"; - -Bypass.prototype.onExecute = function() -{ - var v = this.getInputData(0); - this.setOutputData(0, v); -} - -LiteGraph.registerNodeType("math/bypass", Bypass ); - - -function ToNumber() -{ - this.addInput("in"); - this.addOutput("out"); -} - -ToNumber.title = "to Number"; -ToNumber.desc = "Cast to number"; - -ToNumber.prototype.onExecute = function() -{ - var v = this.getInputData(0); - this.setOutputData(0, Number(v) ); -} - -LiteGraph.registerNodeType("math/to_number", ToNumber ); - - -function MathRange() -{ - this.addInput("in","number",{locked:true}); - this.addOutput("out","number",{locked:true}); - - this.addProperty( "in", 0 ); - this.addProperty( "in_min", 0 ); - this.addProperty( "in_max", 1 ); - this.addProperty( "out_min", 0 ); - this.addProperty( "out_max", 1 ); - - this.size = [80,20]; -} - -MathRange.title = "Range"; -MathRange.desc = "Convert a number from one range to another"; - -MathRange.prototype.getTitle = function() -{ - if(this.flags.collapsed) - return (this._last_v || 0).toFixed(2); - return this.title; -} - -MathRange.prototype.onExecute = function() -{ - if(this.inputs) - for(var i = 0; i < this.inputs.length; i++) - { - var input = this.inputs[i]; - var v = this.getInputData(i); - if(v === undefined) - continue; - this.properties[ input.name ] = v; - } - - var v = this.properties["in"]; - if(v === undefined || v === null || v.constructor !== Number) - v = 0; - - var in_min = this.properties.in_min; - var in_max = this.properties.in_max; - var out_min = this.properties.out_min; - var out_max = this.properties.out_max; - - this._last_v = ((v - in_min) / (in_max - in_min)) * (out_max - out_min) + out_min; - this.setOutputData(0, this._last_v ); -} - -MathRange.prototype.onDrawBackground = function(ctx) -{ - //show the current value - if(this._last_v) - this.outputs[0].label = this._last_v.toFixed(3); - else - this.outputs[0].label = "?"; -} - -MathRange.prototype.onGetInputs = function() { - return [["in_min","number"],["in_max","number"],["out_min","number"],["out_max","number"]]; -} - -LiteGraph.registerNodeType("math/range", MathRange); - - - -function MathRand() -{ - this.addOutput("value","number"); - this.addProperty( "min", 0 ); - this.addProperty( "max", 1 ); - this.size = [60,20]; -} - -MathRand.title = "Rand"; -MathRand.desc = "Random number"; - -MathRand.prototype.onExecute = function() -{ - if(this.inputs) - for(var i = 0; i < this.inputs.length; i++) - { - var input = this.inputs[i]; - var v = this.getInputData(i); - if(v === undefined) - continue; - this.properties[input.name] = v; - } - - var min = this.properties.min; - var max = this.properties.max; - this._last_v = Math.random() * (max-min) + min; - this.setOutputData(0, this._last_v ); -} - -MathRand.prototype.onDrawBackground = function(ctx) -{ - //show the current value - if(this._last_v) - this.outputs[0].label = this._last_v.toFixed(3); - else - this.outputs[0].label = "?"; -} - -MathRand.prototype.onGetInputs = function() { - return [["min","number"],["max","number"]]; -} - -LiteGraph.registerNodeType("math/rand", MathRand); - -//Math clamp -function MathClamp() -{ - this.addInput("in","number"); - this.addOutput("out","number"); - this.size = [60,20]; - this.addProperty( "min", 0 ); - this.addProperty( "max", 1 ); -} - -MathClamp.title = "Clamp"; -MathClamp.desc = "Clamp number between min and max"; -MathClamp.filter = "shader"; - -MathClamp.prototype.onExecute = function() -{ - var v = this.getInputData(0); - if(v == null) return; - v = Math.max(this.properties.min,v); - v = Math.min(this.properties.max,v); - this.setOutputData(0, v ); -} - -MathClamp.prototype.getCode = function(lang) -{ - var code = ""; - if(this.isInputConnected(0)) - code += "clamp({{0}}," + this.properties.min + "," + this.properties.max + ")"; - return code; -} - -LiteGraph.registerNodeType("math/clamp", MathClamp ); - - - -//Math ABS -function MathLerp() -{ - this.properties = { f: 0.5 }; - this.addInput("A","number"); - this.addInput("B","number"); - - this.addOutput("out","number"); -} - -MathLerp.title = "Lerp"; -MathLerp.desc = "Linear Interpolation"; - -MathLerp.prototype.onExecute = function() -{ - var v1 = this.getInputData(0); - if(v1 == null) - v1 = 0; - var v2 = this.getInputData(1); - if(v2 == null) - v2 = 0; - - var f = this.properties.f; - - var _f = this.getInputData(2); - if(_f !== undefined) - f = _f; - - this.setOutputData(0, v1 * (1-f) + v2 * f ); -} - -MathLerp.prototype.onGetInputs = function() -{ - return [["f","number"]]; -} - -LiteGraph.registerNodeType("math/lerp", MathLerp); - - - -//Math ABS -function MathAbs() -{ - this.addInput("in","number"); - this.addOutput("out","number"); - this.size = [60,20]; -} - -MathAbs.title = "Abs"; -MathAbs.desc = "Absolute"; - -MathAbs.prototype.onExecute = function() -{ - var v = this.getInputData(0); - if(v == null) return; - this.setOutputData(0, Math.abs(v) ); -} - -LiteGraph.registerNodeType("math/abs", MathAbs); - - -//Math Floor -function MathFloor() -{ - this.addInput("in","number"); - this.addOutput("out","number"); - this.size = [60,20]; -} - -MathFloor.title = "Floor"; -MathFloor.desc = "Floor number to remove fractional part"; - -MathFloor.prototype.onExecute = function() -{ - var v = this.getInputData(0); - if(v == null) return; - this.setOutputData(0, Math.floor(v) ); -} - -LiteGraph.registerNodeType("math/floor", MathFloor ); - - -//Math frac -function MathFrac() -{ - this.addInput("in","number"); - this.addOutput("out","number"); - this.size = [60,20]; -} - -MathFrac.title = "Frac"; -MathFrac.desc = "Returns fractional part"; - -MathFrac.prototype.onExecute = function() -{ - var v = this.getInputData(0); - if(v == null) - return; - this.setOutputData(0, v%1 ); -} - -LiteGraph.registerNodeType("math/frac",MathFrac); - - -//Math Floor -function MathSmoothStep() -{ - this.addInput("in","number"); - this.addOutput("out","number"); - this.size = [60,20]; - this.properties = { A: 0, B: 1 }; -} - -MathSmoothStep.title = "Smoothstep"; -MathSmoothStep.desc = "Smoothstep"; - -MathSmoothStep.prototype.onExecute = function() -{ - var v = this.getInputData(0); - if(v === undefined) - return; - - var edge0 = this.properties.A; - var edge1 = this.properties.B; - - // Scale, bias and saturate x to 0..1 range - v = Math.clamp((v - edge0)/(edge1 - edge0), 0.0, 1.0); - // Evaluate polynomial - v = v*v*(3 - 2*v); - - this.setOutputData(0, v ); -} - -LiteGraph.registerNodeType("math/smoothstep", MathSmoothStep ); - -//Math scale -function MathScale() -{ - this.addInput("in","number",{label:""}); - this.addOutput("out","number",{label:""}); - this.size = [60,20]; - this.addProperty( "factor", 1 ); -} - -MathScale.title = "Scale"; -MathScale.desc = "v * factor"; - -MathScale.prototype.onExecute = function() -{ - var value = this.getInputData(0); - if(value != null) - this.setOutputData(0, value * this.properties.factor ); -} - -LiteGraph.registerNodeType("math/scale", MathScale ); - - -//Math Average -function MathAverageFilter() -{ - this.addInput("in","number"); - this.addOutput("out","number"); - this.size = [60,20]; - this.addProperty( "samples", 10 ); - this._values = new Float32Array(10); - this._current = 0; -} - -MathAverageFilter.title = "Average"; -MathAverageFilter.desc = "Average Filter"; - -MathAverageFilter.prototype.onExecute = function() -{ - var v = this.getInputData(0); - if(v == null) - v = 0; - - var num_samples = this._values.length; - - this._values[ this._current % num_samples ] = v; - this._current += 1; - if(this._current > num_samples) - this._current = 0; - - var avr = 0; - for(var i = 0; i < num_samples; ++i) - avr += this._values[i]; - - this.setOutputData( 0, avr / num_samples ); -} - -MathAverageFilter.prototype.onPropertyChanged = function( name, value ) -{ - if(value < 1) - value = 1; - this.properties.samples = Math.round(value); - var old = this._values; - - this._values = new Float32Array( this.properties.samples ); - if(old.length <= this._values.length ) - this._values.set(old); - else - this._values.set( old.subarray( 0, this._values.length ) ); -} - -LiteGraph.registerNodeType("math/average", MathAverageFilter ); - - -//Math -function MathTendTo() -{ - this.addInput("in","number"); - this.addOutput("out","number"); - this.addProperty( "factor", 0.1 ); - this.size = [60,20]; - this._value = null; -} - -MathTendTo.title = "TendTo"; -MathTendTo.desc = "moves the output value always closer to the input"; - -MathTendTo.prototype.onExecute = function() -{ - var v = this.getInputData(0); - if(v == null) - v = 0; - var f = this.properties.factor; - if(this._value == null) - this._value = v; - else - this._value = this._value * (1 - f) + v * f; - this.setOutputData( 0, this._value ); -} - -LiteGraph.registerNodeType("math/tendTo", MathTendTo ); - - -//Math operation -function MathOperation() -{ - this.addInput("A","number"); - this.addInput("B","number"); - this.addOutput("=","number"); - this.addProperty( "A", 1 ); - this.addProperty( "B", 1 ); - this.addProperty( "OP", "+", "enum", { values: MathOperation.values } ); -} - -MathOperation.values = ["+","-","*","/","%","^"]; - -MathOperation.title = "Operation"; -MathOperation.desc = "Easy math operators"; -MathOperation["@OP"] = { type:"enum", title: "operation", values: MathOperation.values }; - -MathOperation.prototype.getTitle = function() -{ - return "A " + this.properties.OP + " B"; -} - -MathOperation.prototype.setValue = function(v) -{ - if( typeof(v) == "string") v = parseFloat(v); - this.properties["value"] = v; -} - -MathOperation.prototype.onExecute = function() -{ - var A = this.getInputData(0); - var B = this.getInputData(1); - if(A!=null) - this.properties["A"] = A; - else - A = this.properties["A"]; - - if(B!=null) - this.properties["B"] = B; - else - B = this.properties["B"]; - - var result = 0; - switch(this.properties.OP) - { - case '+': result = A+B; break; - case '-': result = A-B; break; - case 'x': - case 'X': - case '*': result = A*B; break; - case '/': result = A/B; break; - case '%': result = A%B; break; - case '^': result = Math.pow(A,B); break; - default: - console.warn("Unknown operation: " + this.properties.OP); - } - this.setOutputData(0, result ); -} - -MathOperation.prototype.onDrawBackground = function(ctx) -{ - if(this.flags.collapsed) - return; - - ctx.font = "40px Arial"; - ctx.fillStyle = "#CCC"; - ctx.textAlign = "center"; - ctx.fillText(this.properties.OP, this.size[0] * 0.5, this.size[1] * 0.35 + LiteGraph.NODE_TITLE_HEIGHT ); - ctx.textAlign = "left"; -} - -LiteGraph.registerNodeType("math/operation", MathOperation ); - - -//Math compare -function MathCompare() -{ - this.addInput( "A","number" ); - this.addInput( "B","number" ); - this.addOutput("A==B","boolean"); - this.addOutput("A!=B","boolean"); - this.addProperty( "A", 0 ); - this.addProperty( "B", 0 ); -} - -MathCompare.title = "Compare"; -MathCompare.desc = "compares between two values"; - -MathCompare.prototype.onExecute = function() -{ - var A = this.getInputData(0); - var B = this.getInputData(1); - if(A !== undefined) - this.properties["A"] = A; - else - A = this.properties["A"]; - - if(B !== undefined) - this.properties["B"] = B; - else - B = this.properties["B"]; - - for(var i = 0, l = this.outputs.length; i < l; ++i) - { - var output = this.outputs[i]; - if(!output.links || !output.links.length) - continue; - switch( output.name ) - { - case "A==B": value = A==B; break; - case "A!=B": value = A!=B; break; - case "A>B": value = A>B; break; - case "A=B": value = A>=B; break; - } - this.setOutputData(i, value ); - } -}; - -MathCompare.prototype.onGetOutputs = function() -{ - return [["A==B","boolean"],["A!=B","boolean"],["A>B","boolean"],["A=B","boolean"],["A<=B","boolean"]]; -} - -LiteGraph.registerNodeType("math/compare",MathCompare); - -LiteGraph.registerSearchboxExtra("math/compare","==", { outputs:[["A==B","boolean"]], title: "A==B" }); -LiteGraph.registerSearchboxExtra("math/compare","!=", { outputs:[["A!=B","boolean"]], title: "A!=B" }); -LiteGraph.registerSearchboxExtra("math/compare",">", { outputs:[["A>B","boolean"]], title: "A>B" }); -LiteGraph.registerSearchboxExtra("math/compare","<", { outputs:[["A=", { outputs:[["A>=B","boolean"]], title: "A>=B" }); -LiteGraph.registerSearchboxExtra("math/compare","<=", { outputs:[["A<=B","boolean"]], title: "A<=B" }); - - -function MathCondition() -{ - this.addInput("A","number"); - this.addInput("B","number"); - this.addOutput("out","boolean"); - this.addProperty( "A", 1 ); - this.addProperty( "B", 1 ); - this.addProperty( "OP", ">", "string", { values: MathCondition.values } ); - - this.size = [60,40]; -} - -MathCondition.values = [">","<","==","!=","<=",">="]; -MathCondition["@OP"] = { type:"enum", title: "operation", values: MathCondition.values }; - -MathCondition.title = "Condition"; -MathCondition.desc = "evaluates condition between A and B"; - -MathCondition.prototype.onExecute = function() -{ - var A = this.getInputData(0); - if(A === undefined) - A = this.properties.A; - else - this.properties.A = A; - - var B = this.getInputData(1); - if(B === undefined) - B = this.properties.B; - else - this.properties.B = B; - - var result = true; - switch(this.properties.OP) - { - case ">": result = A>B; break; - case "<": result = A=": result = A>=B; break; - } - - this.setOutputData(0, result ); -} - -LiteGraph.registerNodeType("math/condition", MathCondition); - - -function MathAccumulate() -{ - this.addInput("inc","number"); - this.addOutput("total","number"); - this.addProperty( "increment", 1 ); - this.addProperty( "value", 0 ); -} - -MathAccumulate.title = "Accumulate"; -MathAccumulate.desc = "Increments a value every time"; - -MathAccumulate.prototype.onExecute = function() -{ - if(this.properties.value === null) - this.properties.value = 0; - - var inc = this.getInputData(0); - if(inc !== null) - this.properties.value += inc; - else - this.properties.value += this.properties.increment; - this.setOutputData(0, this.properties.value ); -} - -LiteGraph.registerNodeType("math/accumulate", MathAccumulate); - -//Math Trigonometry -function MathTrigonometry() -{ - this.addInput("v","number"); - this.addOutput("sin","number"); - - this.addProperty( "amplitude", 1 ); - this.addProperty( "offset", 0 ); - this.bgImageUrl = "nodes/imgs/icon-sin.png"; -} - -MathTrigonometry.title = "Trigonometry"; -MathTrigonometry.desc = "Sin Cos Tan"; -MathTrigonometry.filter = "shader"; - -MathTrigonometry.prototype.onExecute = function() -{ - var v = this.getInputData(0); - if(v == null) - v = 0; - var amplitude = this.properties["amplitude"]; - var slot = this.findInputSlot("amplitude"); - if(slot != -1) - amplitude = this.getInputData(slot); - var offset = this.properties["offset"]; - slot = this.findInputSlot("offset"); - if(slot != -1) - offset = this.getInputData(slot); - - for(var i = 0, l = this.outputs.length; i < l; ++i) - { - var output = this.outputs[i]; - switch( output.name ) - { - case "sin": value = Math.sin(v); break; - case "cos": value = Math.cos(v); break; - case "tan": value = Math.tan(v); break; - case "asin": value = Math.asin(v); break; - case "acos": value = Math.acos(v); break; - case "atan": value = Math.atan(v); break; - } - this.setOutputData(i, amplitude * value + offset); - } -} - -MathTrigonometry.prototype.onGetInputs = function() -{ - return [["v","number"],["amplitude","number"],["offset","number"]]; -} - - -MathTrigonometry.prototype.onGetOutputs = function() -{ - return [["sin","number"],["cos","number"],["tan","number"],["asin","number"],["acos","number"],["atan","number"]]; -} - - -LiteGraph.registerNodeType("math/trigonometry", MathTrigonometry ); - -LiteGraph.registerSearchboxExtra("math/trigonometry","SIN()", { outputs:[["sin","number"]], title: "SIN()" }); -LiteGraph.registerSearchboxExtra("math/trigonometry","COS()", { outputs:[["cos","number"]], title: "COS()" }); -LiteGraph.registerSearchboxExtra("math/trigonometry","TAN()", { outputs:[["tan","number"]], title: "TAN()" }); - - -//math library for safe math operations without eval -function MathFormula() -{ - this.addInput("x","number"); - this.addInput("y","number"); - this.addOutput("","number"); - this.properties = {x:1.0, y:1.0, formula:"x+y"}; - this.addWidget("toggle","allow",LiteGraph.allow_scripts,function(v){ LiteGraph.allow_scripts = v; }); - this._func = null; -} - -MathFormula.title = "Formula"; -MathFormula.desc = "Compute formula"; - -MathFormula.prototype.onExecute = function() -{ - if(!LiteGraph.allow_scripts) - return; - - var x = this.getInputData(0); - var y = this.getInputData(1); - if(x != null) - this.properties["x"] = x; - else - x = this.properties["x"]; - - if(y!=null) - this.properties["y"] = y; - else - y = this.properties["y"]; - - var f = this.properties["formula"]; - - if(!this._func || this._func_code != this.properties.formula) - { - this._func = new Function( "x","y","TIME", "return " + this.properties.formula ); - this._func_code = this.properties.formula; - } - - var value = this._func(x,y,this.graph.globaltime); - this.setOutputData(0, value ); -} - -MathFormula.prototype.getTitle = function() -{ - return this._func_code || ""; -} - -MathFormula.prototype.onDrawBackground = function() -{ - var f = this.properties["formula"]; - if(this.outputs && this.outputs.length) - this.outputs[0].label = f; -} - -LiteGraph.registerNodeType("math/formula", MathFormula ); - - -function Math3DVec2ToXYZ() -{ - this.addInput("vec2","vec2"); - this.addOutput("x","number"); - this.addOutput("y","number"); -} - -Math3DVec2ToXYZ.title = "Vec2->XY"; -Math3DVec2ToXYZ.desc = "vector 2 to components"; - -Math3DVec2ToXYZ.prototype.onExecute = function() -{ - var v = this.getInputData(0); - if(v == null) return; - - this.setOutputData( 0, v[0] ); - this.setOutputData( 1, v[1] ); -} - -LiteGraph.registerNodeType("math3d/vec2-to-xyz", Math3DVec2ToXYZ ); - - -function Math3DXYToVec2() -{ - this.addInputs([["x","number"],["y","number"]]); - this.addOutput("vec2","vec2"); - this.properties = {x:0, y:0}; - this._data = new Float32Array(2); -} - -Math3DXYToVec2.title = "XY->Vec2"; -Math3DXYToVec2.desc = "components to vector2"; - -Math3DXYToVec2.prototype.onExecute = function() -{ - var x = this.getInputData(0); - if(x == null) x = this.properties.x; - var y = this.getInputData(1); - if(y == null) y = this.properties.y; - - var data = this._data; - data[0] = x; - data[1] = y; - - this.setOutputData( 0, data ); -} - -LiteGraph.registerNodeType("math3d/xy-to-vec2", Math3DXYToVec2 ); - - - - -function Math3DVec3ToXYZ() -{ - this.addInput("vec3","vec3"); - this.addOutput("x","number"); - this.addOutput("y","number"); - this.addOutput("z","number"); -} - -Math3DVec3ToXYZ.title = "Vec3->XYZ"; -Math3DVec3ToXYZ.desc = "vector 3 to components"; - -Math3DVec3ToXYZ.prototype.onExecute = function() -{ - var v = this.getInputData(0); - if(v == null) return; - - this.setOutputData( 0, v[0] ); - this.setOutputData( 1, v[1] ); - this.setOutputData( 2, v[2] ); -} - -LiteGraph.registerNodeType("math3d/vec3-to-xyz", Math3DVec3ToXYZ ); - - -function Math3DXYZToVec3() -{ - this.addInputs([["x","number"],["y","number"],["z","number"]]); - this.addOutput("vec3","vec3"); - this.properties = {x:0, y:0, z:0}; - this._data = new Float32Array(3); -} - -Math3DXYZToVec3.title = "XYZ->Vec3"; -Math3DXYZToVec3.desc = "components to vector3"; - -Math3DXYZToVec3.prototype.onExecute = function() -{ - var x = this.getInputData(0); - if(x == null) x = this.properties.x; - var y = this.getInputData(1); - if(y == null) y = this.properties.y; - var z = this.getInputData(2); - if(z == null) z = this.properties.z; - - var data = this._data; - data[0] = x; - data[1] = y; - data[2] = z; - - this.setOutputData( 0, data ); -} - -LiteGraph.registerNodeType("math3d/xyz-to-vec3", Math3DXYZToVec3 ); - - - -function Math3DVec4ToXYZW() -{ - this.addInput("vec4","vec4"); - this.addOutput("x","number"); - this.addOutput("y","number"); - this.addOutput("z","number"); - this.addOutput("w","number"); -} - -Math3DVec4ToXYZW.title = "Vec4->XYZW"; -Math3DVec4ToXYZW.desc = "vector 4 to components"; - -Math3DVec4ToXYZW.prototype.onExecute = function() -{ - var v = this.getInputData(0); - if(v == null) return; - - this.setOutputData( 0, v[0] ); - this.setOutputData( 1, v[1] ); - this.setOutputData( 2, v[2] ); - this.setOutputData( 3, v[3] ); -} - -LiteGraph.registerNodeType("math3d/vec4-to-xyzw", Math3DVec4ToXYZW ); - - -function Math3DXYZWToVec4() -{ - this.addInputs([["x","number"],["y","number"],["z","number"],["w","number"]]); - this.addOutput("vec4","vec4"); - this.properties = {x:0, y:0, z:0, w:0}; - this._data = new Float32Array(4); -} - -Math3DXYZWToVec4.title = "XYZW->Vec4"; -Math3DXYZWToVec4.desc = "components to vector4"; - -Math3DXYZWToVec4.prototype.onExecute = function() -{ - var x = this.getInputData(0); - if(x == null) x = this.properties.x; - var y = this.getInputData(1); - if(y == null) y = this.properties.y; - var z = this.getInputData(2); - if(z == null) z = this.properties.z; - var w = this.getInputData(3); - if(w == null) w = this.properties.w; - - var data = this._data; - data[0] = x; - data[1] = y; - data[2] = z; - data[3] = w; - - this.setOutputData( 0, data ); -} - -LiteGraph.registerNodeType("math3d/xyzw-to-vec4", Math3DXYZWToVec4 ); - - - - -//if glMatrix is installed... -if(global.glMatrix) -{ - - function Math3DQuaternion() - { - this.addOutput("quat","quat"); - this.properties = { x:0, y:0, z:0, w: 1 }; - this._value = quat.create(); - } - - Math3DQuaternion.title = "Quaternion"; - Math3DQuaternion.desc = "quaternion"; - - Math3DQuaternion.prototype.onExecute = function() - { - this._value[0] = this.properties.x; - this._value[1] = this.properties.y; - this._value[2] = this.properties.z; - this._value[3] = this.properties.w; - this.setOutputData( 0, this._value ); - } - - LiteGraph.registerNodeType("math3d/quaternion", Math3DQuaternion ); - - - function Math3DRotation() - { - this.addInputs([["degrees","number"],["axis","vec3"]]); - this.addOutput("quat","quat"); - this.properties = { angle:90.0, axis: vec3.fromValues(0,1,0) }; - - this._value = quat.create(); - } - - Math3DRotation.title = "Rotation"; - Math3DRotation.desc = "quaternion rotation"; - - Math3DRotation.prototype.onExecute = function() - { - var angle = this.getInputData(0); - if(angle == null) angle = this.properties.angle; - var axis = this.getInputData(1); - if(axis == null) axis = this.properties.axis; - - var R = quat.setAxisAngle( this._value, axis, angle * 0.0174532925 ); - this.setOutputData( 0, R ); - } - - - LiteGraph.registerNodeType("math3d/rotation", Math3DRotation ); - - - //Math3D rotate vec3 - function Math3DRotateVec3() - { - this.addInputs([["vec3","vec3"],["quat","quat"]]); - this.addOutput("result","vec3"); - this.properties = { vec: [0,0,1] }; - } - - Math3DRotateVec3.title = "Rot. Vec3"; - Math3DRotateVec3.desc = "rotate a point"; - - Math3DRotateVec3.prototype.onExecute = function() - { - var vec = this.getInputData(0); - if(vec == null) vec = this.properties.vec; - var quat = this.getInputData(1); - if(quat == null) - this.setOutputData(vec); - else - this.setOutputData( 0, vec3.transformQuat( vec3.create(), vec, quat ) ); - } - - LiteGraph.registerNodeType("math3d/rotate_vec3", Math3DRotateVec3); - - - - function Math3DMultQuat() - { - this.addInputs( [["A","quat"],["B","quat"]] ); - this.addOutput( "A*B","quat" ); - - this._value = quat.create(); - } - - Math3DMultQuat.title = "Mult. Quat"; - Math3DMultQuat.desc = "rotate quaternion"; - - Math3DMultQuat.prototype.onExecute = function() - { - var A = this.getInputData(0); - if(A == null) return; - var B = this.getInputData(1); - if(B == null) return; - - var R = quat.multiply( this._value, A, B ); - this.setOutputData( 0, R ); - } - - LiteGraph.registerNodeType("math3d/mult-quat", Math3DMultQuat ); - - - function Math3DQuatSlerp() - { - this.addInputs( [["A","quat"],["B","quat"],["factor","number"]] ); - this.addOutput( "slerp","quat" ); - this.addProperty( "factor", 0.5 ); - - this._value = quat.create(); - } - - Math3DQuatSlerp.title = "Quat Slerp"; - Math3DQuatSlerp.desc = "quaternion spherical interpolation"; - - Math3DQuatSlerp.prototype.onExecute = function() - { - var A = this.getInputData(0); - if(A == null) - return; - var B = this.getInputData(1); - if(B == null) - return; - var factor = this.properties.factor; - if( this.getInputData(2) != null ) - factor = this.getInputData(2); - - var R = quat.slerp( this._value, A, B, factor ); - this.setOutputData( 0, R ); - } - - LiteGraph.registerNodeType("math3d/quat-slerp", Math3DQuatSlerp ); - -} //glMatrix - +(function(global){ +var LiteGraph = global.LiteGraph; + +//Converter +function Converter() +{ + this.addInput("in","*"); + this.size = [60,20]; +} + +Converter.title = "Converter"; +Converter.desc = "type A to type B"; + +Converter.prototype.onExecute = function() +{ + var v = this.getInputData(0); + if(v == null) + return; + + if(this.outputs) + for(var i = 0; i < this.outputs.length; i++) + { + var output = this.outputs[i]; + if(!output.links || !output.links.length) + continue; + + var result = null; + switch( output.name ) + { + case "number": result = v.length ? v[0] : parseFloat(v); break; + case "vec2": + case "vec3": + case "vec4": + var result = null; + var count = 1; + switch(output.name) + { + case "vec2": count = 2; break; + case "vec3": count = 3; break; + case "vec4": count = 4; break; + } + + var result = new Float32Array( count ); + if( v.length ) + { + for(var j = 0; j < v.length && j < result.length; j++) + result[j] = v[j]; + } + else + result[0] = parseFloat(v); + break; + } + this.setOutputData(i, result); + } +} + +Converter.prototype.onGetOutputs = function() { + return [["number","number"],["vec2","vec2"],["vec3","vec3"],["vec4","vec4"]]; +} + +LiteGraph.registerNodeType("math/converter", Converter ); + + +//Bypass +function Bypass() +{ + this.addInput("in"); + this.addOutput("out"); + this.size = [60,20]; +} + +Bypass.title = "Bypass"; +Bypass.desc = "removes the type"; + +Bypass.prototype.onExecute = function() +{ + var v = this.getInputData(0); + this.setOutputData(0, v); +} + +LiteGraph.registerNodeType("math/bypass", Bypass ); + + +function ToNumber() +{ + this.addInput("in"); + this.addOutput("out"); +} + +ToNumber.title = "to Number"; +ToNumber.desc = "Cast to number"; + +ToNumber.prototype.onExecute = function() +{ + var v = this.getInputData(0); + this.setOutputData(0, Number(v) ); +} + +LiteGraph.registerNodeType("math/to_number", ToNumber ); + + +function MathRange() +{ + this.addInput("in","number",{locked:true}); + this.addOutput("out","number",{locked:true}); + + this.addProperty( "in", 0 ); + this.addProperty( "in_min", 0 ); + this.addProperty( "in_max", 1 ); + this.addProperty( "out_min", 0 ); + this.addProperty( "out_max", 1 ); + + this.size = [80,20]; +} + +MathRange.title = "Range"; +MathRange.desc = "Convert a number from one range to another"; + +MathRange.prototype.getTitle = function() +{ + if(this.flags.collapsed) + return (this._last_v || 0).toFixed(2); + return this.title; +} + +MathRange.prototype.onExecute = function() +{ + if(this.inputs) + for(var i = 0; i < this.inputs.length; i++) + { + var input = this.inputs[i]; + var v = this.getInputData(i); + if(v === undefined) + continue; + this.properties[ input.name ] = v; + } + + var v = this.properties["in"]; + if(v === undefined || v === null || v.constructor !== Number) + v = 0; + + var in_min = this.properties.in_min; + var in_max = this.properties.in_max; + var out_min = this.properties.out_min; + var out_max = this.properties.out_max; + + this._last_v = ((v - in_min) / (in_max - in_min)) * (out_max - out_min) + out_min; + this.setOutputData(0, this._last_v ); +} + +MathRange.prototype.onDrawBackground = function(ctx) +{ + //show the current value + if(this._last_v) + this.outputs[0].label = this._last_v.toFixed(3); + else + this.outputs[0].label = "?"; +} + +MathRange.prototype.onGetInputs = function() { + return [["in_min","number"],["in_max","number"],["out_min","number"],["out_max","number"]]; +} + +LiteGraph.registerNodeType("math/range", MathRange); + + + +function MathRand() +{ + this.addOutput("value","number"); + this.addProperty( "min", 0 ); + this.addProperty( "max", 1 ); + this.size = [60,20]; +} + +MathRand.title = "Rand"; +MathRand.desc = "Random number"; + +MathRand.prototype.onExecute = function() +{ + if(this.inputs) + for(var i = 0; i < this.inputs.length; i++) + { + var input = this.inputs[i]; + var v = this.getInputData(i); + if(v === undefined) + continue; + this.properties[input.name] = v; + } + + var min = this.properties.min; + var max = this.properties.max; + this._last_v = Math.random() * (max-min) + min; + this.setOutputData(0, this._last_v ); +} + +MathRand.prototype.onDrawBackground = function(ctx) +{ + //show the current value + if(this._last_v) + this.outputs[0].label = this._last_v.toFixed(3); + else + this.outputs[0].label = "?"; +} + +MathRand.prototype.onGetInputs = function() { + return [["min","number"],["max","number"]]; +} + +LiteGraph.registerNodeType("math/rand", MathRand); + +//Math clamp +function MathClamp() +{ + this.addInput("in","number"); + this.addOutput("out","number"); + this.size = [60,20]; + this.addProperty( "min", 0 ); + this.addProperty( "max", 1 ); +} + +MathClamp.title = "Clamp"; +MathClamp.desc = "Clamp number between min and max"; +MathClamp.filter = "shader"; + +MathClamp.prototype.onExecute = function() +{ + var v = this.getInputData(0); + if(v == null) return; + v = Math.max(this.properties.min,v); + v = Math.min(this.properties.max,v); + this.setOutputData(0, v ); +} + +MathClamp.prototype.getCode = function(lang) +{ + var code = ""; + if(this.isInputConnected(0)) + code += "clamp({{0}}," + this.properties.min + "," + this.properties.max + ")"; + return code; +} + +LiteGraph.registerNodeType("math/clamp", MathClamp ); + + + +//Math ABS +function MathLerp() +{ + this.properties = { f: 0.5 }; + this.addInput("A","number"); + this.addInput("B","number"); + + this.addOutput("out","number"); +} + +MathLerp.title = "Lerp"; +MathLerp.desc = "Linear Interpolation"; + +MathLerp.prototype.onExecute = function() +{ + var v1 = this.getInputData(0); + if(v1 == null) + v1 = 0; + var v2 = this.getInputData(1); + if(v2 == null) + v2 = 0; + + var f = this.properties.f; + + var _f = this.getInputData(2); + if(_f !== undefined) + f = _f; + + this.setOutputData(0, v1 * (1-f) + v2 * f ); +} + +MathLerp.prototype.onGetInputs = function() +{ + return [["f","number"]]; +} + +LiteGraph.registerNodeType("math/lerp", MathLerp); + + + +//Math ABS +function MathAbs() +{ + this.addInput("in","number"); + this.addOutput("out","number"); + this.size = [60,20]; +} + +MathAbs.title = "Abs"; +MathAbs.desc = "Absolute"; + +MathAbs.prototype.onExecute = function() +{ + var v = this.getInputData(0); + if(v == null) return; + this.setOutputData(0, Math.abs(v) ); +} + +LiteGraph.registerNodeType("math/abs", MathAbs); + + +//Math Floor +function MathFloor() +{ + this.addInput("in","number"); + this.addOutput("out","number"); + this.size = [60,20]; +} + +MathFloor.title = "Floor"; +MathFloor.desc = "Floor number to remove fractional part"; + +MathFloor.prototype.onExecute = function() +{ + var v = this.getInputData(0); + if(v == null) return; + this.setOutputData(0, Math.floor(v) ); +} + +LiteGraph.registerNodeType("math/floor", MathFloor ); + + +//Math frac +function MathFrac() +{ + this.addInput("in","number"); + this.addOutput("out","number"); + this.size = [60,20]; +} + +MathFrac.title = "Frac"; +MathFrac.desc = "Returns fractional part"; + +MathFrac.prototype.onExecute = function() +{ + var v = this.getInputData(0); + if(v == null) + return; + this.setOutputData(0, v%1 ); +} + +LiteGraph.registerNodeType("math/frac",MathFrac); + + +//Math Floor +function MathSmoothStep() +{ + this.addInput("in","number"); + this.addOutput("out","number"); + this.size = [60,20]; + this.properties = { A: 0, B: 1 }; +} + +MathSmoothStep.title = "Smoothstep"; +MathSmoothStep.desc = "Smoothstep"; + +MathSmoothStep.prototype.onExecute = function() +{ + var v = this.getInputData(0); + if(v === undefined) + return; + + var edge0 = this.properties.A; + var edge1 = this.properties.B; + + // Scale, bias and saturate x to 0..1 range + v = Math.clamp((v - edge0)/(edge1 - edge0), 0.0, 1.0); + // Evaluate polynomial + v = v*v*(3 - 2*v); + + this.setOutputData(0, v ); +} + +LiteGraph.registerNodeType("math/smoothstep", MathSmoothStep ); + +//Math scale +function MathScale() +{ + this.addInput("in","number",{label:""}); + this.addOutput("out","number",{label:""}); + this.size = [60,20]; + this.addProperty( "factor", 1 ); +} + +MathScale.title = "Scale"; +MathScale.desc = "v * factor"; + +MathScale.prototype.onExecute = function() +{ + var value = this.getInputData(0); + if(value != null) + this.setOutputData(0, value * this.properties.factor ); +} + +LiteGraph.registerNodeType("math/scale", MathScale ); + + +//Math Average +function MathAverageFilter() +{ + this.addInput("in","number"); + this.addOutput("out","number"); + this.size = [60,20]; + this.addProperty( "samples", 10 ); + this._values = new Float32Array(10); + this._current = 0; +} + +MathAverageFilter.title = "Average"; +MathAverageFilter.desc = "Average Filter"; + +MathAverageFilter.prototype.onExecute = function() +{ + var v = this.getInputData(0); + if(v == null) + v = 0; + + var num_samples = this._values.length; + + this._values[ this._current % num_samples ] = v; + this._current += 1; + if(this._current > num_samples) + this._current = 0; + + var avr = 0; + for(var i = 0; i < num_samples; ++i) + avr += this._values[i]; + + this.setOutputData( 0, avr / num_samples ); +} + +MathAverageFilter.prototype.onPropertyChanged = function( name, value ) +{ + if(value < 1) + value = 1; + this.properties.samples = Math.round(value); + var old = this._values; + + this._values = new Float32Array( this.properties.samples ); + if(old.length <= this._values.length ) + this._values.set(old); + else + this._values.set( old.subarray( 0, this._values.length ) ); +} + +LiteGraph.registerNodeType("math/average", MathAverageFilter ); + + +//Math +function MathTendTo() +{ + this.addInput("in","number"); + this.addOutput("out","number"); + this.addProperty( "factor", 0.1 ); + this.size = [60,20]; + this._value = null; +} + +MathTendTo.title = "TendTo"; +MathTendTo.desc = "moves the output value always closer to the input"; + +MathTendTo.prototype.onExecute = function() +{ + var v = this.getInputData(0); + if(v == null) + v = 0; + var f = this.properties.factor; + if(this._value == null) + this._value = v; + else + this._value = this._value * (1 - f) + v * f; + this.setOutputData( 0, this._value ); +} + +LiteGraph.registerNodeType("math/tendTo", MathTendTo ); + + +//Math operation +function MathOperation() +{ + this.addInput("A","number"); + this.addInput("B","number"); + this.addOutput("=","number"); + this.addProperty( "A", 1 ); + this.addProperty( "B", 1 ); + this.addProperty( "OP", "+", "enum", { values: MathOperation.values } ); +} + +MathOperation.values = ["+","-","*","/","%","^"]; + +MathOperation.title = "Operation"; +MathOperation.desc = "Easy math operators"; +MathOperation["@OP"] = { type:"enum", title: "operation", values: MathOperation.values }; + +MathOperation.prototype.getTitle = function() +{ + return "A " + this.properties.OP + " B"; +} + +MathOperation.prototype.setValue = function(v) +{ + if( typeof(v) == "string") v = parseFloat(v); + this.properties["value"] = v; +} + +MathOperation.prototype.onExecute = function() +{ + var A = this.getInputData(0); + var B = this.getInputData(1); + if(A!=null) + this.properties["A"] = A; + else + A = this.properties["A"]; + + if(B!=null) + this.properties["B"] = B; + else + B = this.properties["B"]; + + var result = 0; + switch(this.properties.OP) + { + case '+': result = A+B; break; + case '-': result = A-B; break; + case 'x': + case 'X': + case '*': result = A*B; break; + case '/': result = A/B; break; + case '%': result = A%B; break; + case '^': result = Math.pow(A,B); break; + default: + console.warn("Unknown operation: " + this.properties.OP); + } + this.setOutputData(0, result ); +} + +MathOperation.prototype.onDrawBackground = function(ctx) +{ + if(this.flags.collapsed) + return; + + ctx.font = "40px Arial"; + ctx.fillStyle = "#CCC"; + ctx.textAlign = "center"; + ctx.fillText(this.properties.OP, this.size[0] * 0.5, this.size[1] * 0.35 + LiteGraph.NODE_TITLE_HEIGHT ); + ctx.textAlign = "left"; +} + +LiteGraph.registerNodeType("math/operation", MathOperation ); + + +//Math compare +function MathCompare() +{ + this.addInput( "A","number" ); + this.addInput( "B","number" ); + this.addOutput("A==B","boolean"); + this.addOutput("A!=B","boolean"); + this.addProperty( "A", 0 ); + this.addProperty( "B", 0 ); +} + +MathCompare.title = "Compare"; +MathCompare.desc = "compares between two values"; + +MathCompare.prototype.onExecute = function() +{ + var A = this.getInputData(0); + var B = this.getInputData(1); + if(A !== undefined) + this.properties["A"] = A; + else + A = this.properties["A"]; + + if(B !== undefined) + this.properties["B"] = B; + else + B = this.properties["B"]; + + for(var i = 0, l = this.outputs.length; i < l; ++i) + { + var output = this.outputs[i]; + if(!output.links || !output.links.length) + continue; + switch( output.name ) + { + case "A==B": value = A==B; break; + case "A!=B": value = A!=B; break; + case "A>B": value = A>B; break; + case "A=B": value = A>=B; break; + } + this.setOutputData(i, value ); + } +}; + +MathCompare.prototype.onGetOutputs = function() +{ + return [["A==B","boolean"],["A!=B","boolean"],["A>B","boolean"],["A=B","boolean"],["A<=B","boolean"]]; +} + +LiteGraph.registerNodeType("math/compare",MathCompare); + +LiteGraph.registerSearchboxExtra("math/compare","==", { outputs:[["A==B","boolean"]], title: "A==B" }); +LiteGraph.registerSearchboxExtra("math/compare","!=", { outputs:[["A!=B","boolean"]], title: "A!=B" }); +LiteGraph.registerSearchboxExtra("math/compare",">", { outputs:[["A>B","boolean"]], title: "A>B" }); +LiteGraph.registerSearchboxExtra("math/compare","<", { outputs:[["A=", { outputs:[["A>=B","boolean"]], title: "A>=B" }); +LiteGraph.registerSearchboxExtra("math/compare","<=", { outputs:[["A<=B","boolean"]], title: "A<=B" }); + + +function MathCondition() +{ + this.addInput("A","number"); + this.addInput("B","number"); + this.addOutput("out","boolean"); + this.addProperty( "A", 1 ); + this.addProperty( "B", 1 ); + this.addProperty( "OP", ">", "string", { values: MathCondition.values } ); + + this.size = [60,40]; +} + +MathCondition.values = [">","<","==","!=","<=",">="]; +MathCondition["@OP"] = { type:"enum", title: "operation", values: MathCondition.values }; + +MathCondition.title = "Condition"; +MathCondition.desc = "evaluates condition between A and B"; + +MathCondition.prototype.onExecute = function() +{ + var A = this.getInputData(0); + if(A === undefined) + A = this.properties.A; + else + this.properties.A = A; + + var B = this.getInputData(1); + if(B === undefined) + B = this.properties.B; + else + this.properties.B = B; + + var result = true; + switch(this.properties.OP) + { + case ">": result = A>B; break; + case "<": result = A=": result = A>=B; break; + } + + this.setOutputData(0, result ); +} + +LiteGraph.registerNodeType("math/condition", MathCondition); + + +function MathAccumulate() +{ + this.addInput("inc","number"); + this.addOutput("total","number"); + this.addProperty( "increment", 1 ); + this.addProperty( "value", 0 ); +} + +MathAccumulate.title = "Accumulate"; +MathAccumulate.desc = "Increments a value every time"; + +MathAccumulate.prototype.onExecute = function() +{ + if(this.properties.value === null) + this.properties.value = 0; + + var inc = this.getInputData(0); + if(inc !== null) + this.properties.value += inc; + else + this.properties.value += this.properties.increment; + this.setOutputData(0, this.properties.value ); +} + +LiteGraph.registerNodeType("math/accumulate", MathAccumulate); + +//Math Trigonometry +function MathTrigonometry() +{ + this.addInput("v","number"); + this.addOutput("sin","number"); + + this.addProperty( "amplitude", 1 ); + this.addProperty( "offset", 0 ); + this.bgImageUrl = "nodes/imgs/icon-sin.png"; +} + +MathTrigonometry.title = "Trigonometry"; +MathTrigonometry.desc = "Sin Cos Tan"; +MathTrigonometry.filter = "shader"; + +MathTrigonometry.prototype.onExecute = function() +{ + var v = this.getInputData(0); + if(v == null) + v = 0; + var amplitude = this.properties["amplitude"]; + var slot = this.findInputSlot("amplitude"); + if(slot != -1) + amplitude = this.getInputData(slot); + var offset = this.properties["offset"]; + slot = this.findInputSlot("offset"); + if(slot != -1) + offset = this.getInputData(slot); + + for(var i = 0, l = this.outputs.length; i < l; ++i) + { + var output = this.outputs[i]; + switch( output.name ) + { + case "sin": value = Math.sin(v); break; + case "cos": value = Math.cos(v); break; + case "tan": value = Math.tan(v); break; + case "asin": value = Math.asin(v); break; + case "acos": value = Math.acos(v); break; + case "atan": value = Math.atan(v); break; + } + this.setOutputData(i, amplitude * value + offset); + } +} + +MathTrigonometry.prototype.onGetInputs = function() +{ + return [["v","number"],["amplitude","number"],["offset","number"]]; +} + + +MathTrigonometry.prototype.onGetOutputs = function() +{ + return [["sin","number"],["cos","number"],["tan","number"],["asin","number"],["acos","number"],["atan","number"]]; +} + + +LiteGraph.registerNodeType("math/trigonometry", MathTrigonometry ); + +LiteGraph.registerSearchboxExtra("math/trigonometry","SIN()", { outputs:[["sin","number"]], title: "SIN()" }); +LiteGraph.registerSearchboxExtra("math/trigonometry","COS()", { outputs:[["cos","number"]], title: "COS()" }); +LiteGraph.registerSearchboxExtra("math/trigonometry","TAN()", { outputs:[["tan","number"]], title: "TAN()" }); + + +//math library for safe math operations without eval +function MathFormula() +{ + this.addInput("x","number"); + this.addInput("y","number"); + this.addOutput("","number"); + this.properties = {x:1.0, y:1.0, formula:"x+y"}; + this.addWidget("toggle","allow",LiteGraph.allow_scripts,function(v){ LiteGraph.allow_scripts = v; }); + this._func = null; +} + +MathFormula.title = "Formula"; +MathFormula.desc = "Compute formula"; + +MathFormula.prototype.onExecute = function() +{ + if(!LiteGraph.allow_scripts) + return; + + var x = this.getInputData(0); + var y = this.getInputData(1); + if(x != null) + this.properties["x"] = x; + else + x = this.properties["x"]; + + if(y!=null) + this.properties["y"] = y; + else + y = this.properties["y"]; + + var f = this.properties["formula"]; + + if(!this._func || this._func_code != this.properties.formula) + { + this._func = new Function( "x","y","TIME", "return " + this.properties.formula ); + this._func_code = this.properties.formula; + } + + var value = this._func(x,y,this.graph.globaltime); + this.setOutputData(0, value ); +} + +MathFormula.prototype.getTitle = function() +{ + return this._func_code || ""; +} + +MathFormula.prototype.onDrawBackground = function() +{ + var f = this.properties["formula"]; + if(this.outputs && this.outputs.length) + this.outputs[0].label = f; +} + +LiteGraph.registerNodeType("math/formula", MathFormula ); + + +function Math3DVec2ToXYZ() +{ + this.addInput("vec2","vec2"); + this.addOutput("x","number"); + this.addOutput("y","number"); +} + +Math3DVec2ToXYZ.title = "Vec2->XY"; +Math3DVec2ToXYZ.desc = "vector 2 to components"; + +Math3DVec2ToXYZ.prototype.onExecute = function() +{ + var v = this.getInputData(0); + if(v == null) return; + + this.setOutputData( 0, v[0] ); + this.setOutputData( 1, v[1] ); +} + +LiteGraph.registerNodeType("math3d/vec2-to-xyz", Math3DVec2ToXYZ ); + + +function Math3DXYToVec2() +{ + this.addInputs([["x","number"],["y","number"]]); + this.addOutput("vec2","vec2"); + this.properties = {x:0, y:0}; + this._data = new Float32Array(2); +} + +Math3DXYToVec2.title = "XY->Vec2"; +Math3DXYToVec2.desc = "components to vector2"; + +Math3DXYToVec2.prototype.onExecute = function() +{ + var x = this.getInputData(0); + if(x == null) x = this.properties.x; + var y = this.getInputData(1); + if(y == null) y = this.properties.y; + + var data = this._data; + data[0] = x; + data[1] = y; + + this.setOutputData( 0, data ); +} + +LiteGraph.registerNodeType("math3d/xy-to-vec2", Math3DXYToVec2 ); + + + + +function Math3DVec3ToXYZ() +{ + this.addInput("vec3","vec3"); + this.addOutput("x","number"); + this.addOutput("y","number"); + this.addOutput("z","number"); +} + +Math3DVec3ToXYZ.title = "Vec3->XYZ"; +Math3DVec3ToXYZ.desc = "vector 3 to components"; + +Math3DVec3ToXYZ.prototype.onExecute = function() +{ + var v = this.getInputData(0); + if(v == null) return; + + this.setOutputData( 0, v[0] ); + this.setOutputData( 1, v[1] ); + this.setOutputData( 2, v[2] ); +} + +LiteGraph.registerNodeType("math3d/vec3-to-xyz", Math3DVec3ToXYZ ); + + +function Math3DXYZToVec3() +{ + this.addInputs([["x","number"],["y","number"],["z","number"]]); + this.addOutput("vec3","vec3"); + this.properties = {x:0, y:0, z:0}; + this._data = new Float32Array(3); +} + +Math3DXYZToVec3.title = "XYZ->Vec3"; +Math3DXYZToVec3.desc = "components to vector3"; + +Math3DXYZToVec3.prototype.onExecute = function() +{ + var x = this.getInputData(0); + if(x == null) x = this.properties.x; + var y = this.getInputData(1); + if(y == null) y = this.properties.y; + var z = this.getInputData(2); + if(z == null) z = this.properties.z; + + var data = this._data; + data[0] = x; + data[1] = y; + data[2] = z; + + this.setOutputData( 0, data ); +} + +LiteGraph.registerNodeType("math3d/xyz-to-vec3", Math3DXYZToVec3 ); + + + +function Math3DVec4ToXYZW() +{ + this.addInput("vec4","vec4"); + this.addOutput("x","number"); + this.addOutput("y","number"); + this.addOutput("z","number"); + this.addOutput("w","number"); +} + +Math3DVec4ToXYZW.title = "Vec4->XYZW"; +Math3DVec4ToXYZW.desc = "vector 4 to components"; + +Math3DVec4ToXYZW.prototype.onExecute = function() +{ + var v = this.getInputData(0); + if(v == null) return; + + this.setOutputData( 0, v[0] ); + this.setOutputData( 1, v[1] ); + this.setOutputData( 2, v[2] ); + this.setOutputData( 3, v[3] ); +} + +LiteGraph.registerNodeType("math3d/vec4-to-xyzw", Math3DVec4ToXYZW ); + + +function Math3DXYZWToVec4() +{ + this.addInputs([["x","number"],["y","number"],["z","number"],["w","number"]]); + this.addOutput("vec4","vec4"); + this.properties = {x:0, y:0, z:0, w:0}; + this._data = new Float32Array(4); +} + +Math3DXYZWToVec4.title = "XYZW->Vec4"; +Math3DXYZWToVec4.desc = "components to vector4"; + +Math3DXYZWToVec4.prototype.onExecute = function() +{ + var x = this.getInputData(0); + if(x == null) x = this.properties.x; + var y = this.getInputData(1); + if(y == null) y = this.properties.y; + var z = this.getInputData(2); + if(z == null) z = this.properties.z; + var w = this.getInputData(3); + if(w == null) w = this.properties.w; + + var data = this._data; + data[0] = x; + data[1] = y; + data[2] = z; + data[3] = w; + + this.setOutputData( 0, data ); +} + +LiteGraph.registerNodeType("math3d/xyzw-to-vec4", Math3DXYZWToVec4 ); + + + + +//if glMatrix is installed... +if(global.glMatrix) +{ + + function Math3DQuaternion() + { + this.addOutput("quat","quat"); + this.properties = { x:0, y:0, z:0, w: 1 }; + this._value = quat.create(); + } + + Math3DQuaternion.title = "Quaternion"; + Math3DQuaternion.desc = "quaternion"; + + Math3DQuaternion.prototype.onExecute = function() + { + this._value[0] = this.properties.x; + this._value[1] = this.properties.y; + this._value[2] = this.properties.z; + this._value[3] = this.properties.w; + this.setOutputData( 0, this._value ); + } + + LiteGraph.registerNodeType("math3d/quaternion", Math3DQuaternion ); + + + function Math3DRotation() + { + this.addInputs([["degrees","number"],["axis","vec3"]]); + this.addOutput("quat","quat"); + this.properties = { angle:90.0, axis: vec3.fromValues(0,1,0) }; + + this._value = quat.create(); + } + + Math3DRotation.title = "Rotation"; + Math3DRotation.desc = "quaternion rotation"; + + Math3DRotation.prototype.onExecute = function() + { + var angle = this.getInputData(0); + if(angle == null) angle = this.properties.angle; + var axis = this.getInputData(1); + if(axis == null) axis = this.properties.axis; + + var R = quat.setAxisAngle( this._value, axis, angle * 0.0174532925 ); + this.setOutputData( 0, R ); + } + + + LiteGraph.registerNodeType("math3d/rotation", Math3DRotation ); + + + //Math3D rotate vec3 + function Math3DRotateVec3() + { + this.addInputs([["vec3","vec3"],["quat","quat"]]); + this.addOutput("result","vec3"); + this.properties = { vec: [0,0,1] }; + } + + Math3DRotateVec3.title = "Rot. Vec3"; + Math3DRotateVec3.desc = "rotate a point"; + + Math3DRotateVec3.prototype.onExecute = function() + { + var vec = this.getInputData(0); + if(vec == null) vec = this.properties.vec; + var quat = this.getInputData(1); + if(quat == null) + this.setOutputData(vec); + else + this.setOutputData( 0, vec3.transformQuat( vec3.create(), vec, quat ) ); + } + + LiteGraph.registerNodeType("math3d/rotate_vec3", Math3DRotateVec3); + + + + function Math3DMultQuat() + { + this.addInputs( [["A","quat"],["B","quat"]] ); + this.addOutput( "A*B","quat" ); + + this._value = quat.create(); + } + + Math3DMultQuat.title = "Mult. Quat"; + Math3DMultQuat.desc = "rotate quaternion"; + + Math3DMultQuat.prototype.onExecute = function() + { + var A = this.getInputData(0); + if(A == null) return; + var B = this.getInputData(1); + if(B == null) return; + + var R = quat.multiply( this._value, A, B ); + this.setOutputData( 0, R ); + } + + LiteGraph.registerNodeType("math3d/mult-quat", Math3DMultQuat ); + + + function Math3DQuatSlerp() + { + this.addInputs( [["A","quat"],["B","quat"],["factor","number"]] ); + this.addOutput( "slerp","quat" ); + this.addProperty( "factor", 0.5 ); + + this._value = quat.create(); + } + + Math3DQuatSlerp.title = "Quat Slerp"; + Math3DQuatSlerp.desc = "quaternion spherical interpolation"; + + Math3DQuatSlerp.prototype.onExecute = function() + { + var A = this.getInputData(0); + if(A == null) + return; + var B = this.getInputData(1); + if(B == null) + return; + var factor = this.properties.factor; + if( this.getInputData(2) != null ) + factor = this.getInputData(2); + + var R = quat.slerp( this._value, A, B, factor ); + this.setOutputData( 0, R ); + } + + LiteGraph.registerNodeType("math3d/quat-slerp", Math3DQuatSlerp ); + +} //glMatrix + })(this); (function(global){ var LiteGraph = global.LiteGraph; @@ -11300,7826 +11301,6973 @@ LiteGraph.registerNodeType("logic/sequence", Sequence ); (function(global){ var LiteGraph = global.LiteGraph; -function GraphicsPlot() +//Works with Litegl.js to create WebGL nodes +global.LGraphTexture = null; + +if(typeof(GL) != "undefined") { - this.addInput("A","Number"); - this.addInput("B","Number"); - this.addInput("C","Number"); - this.addInput("D","Number"); - this.values = [[],[],[],[]]; - this.properties = { scale: 2 }; -} + LGraphCanvas.link_type_colors["Texture"] = "#AEF"; -GraphicsPlot.title = "Plot"; -GraphicsPlot.desc = "Plots data over time"; -GraphicsPlot.colors = ["#FFF","#F99","#9F9","#99F"]; - -GraphicsPlot.prototype.onExecute = function(ctx) -{ - if(this.flags.collapsed) - return; - - var size = this.size; - - for(var i = 0; i < 4; ++i) + function LGraphTexture() { - var v = this.getInputData(i); - if(v == null) - continue; - var values = this.values[i]; - values.push(v); - if(values.length > size[0]) - values.shift(); - } -} - -GraphicsPlot.prototype.onDrawBackground = function(ctx) -{ - if(this.flags.collapsed) - return; - - var size = this.size; - - var scale = 0.5 * size[1] / this.properties.scale; - var colors = GraphicsPlot.colors; - var offset = size[1] * 0.5; - - ctx.fillStyle = "#000"; - ctx.fillRect(0,0, size[0],size[1]); - ctx.strokeStyle = "#555"; - ctx.beginPath(); - ctx.moveTo(0, offset); - ctx.lineTo(size[0], offset); - ctx.stroke(); - - if( this.inputs ) - for(var i = 0; i < 4; ++i) - { - var values = this.values[i]; - if( !this.inputs[i] || !this.inputs[i].link ) - continue; - ctx.strokeStyle = colors[i]; - ctx.beginPath(); - var v = values[0] * scale * -1 + offset; - ctx.moveTo(0, Math.clamp( v, 0, size[1]) ); - for(var j = 1; j < values.length && j < size[0]; ++j) - { - var v = values[j] * scale * -1 + offset; - ctx.lineTo( j, Math.clamp( v, 0, size[1]) ); - } - ctx.stroke(); - } -} - -LiteGraph.registerNodeType("graphics/plot", GraphicsPlot); - - -function GraphicsImage() -{ - this.addOutput("frame","image"); - this.properties = {"url":""}; -} - -GraphicsImage.title = "Image"; -GraphicsImage.desc = "Image loader"; -GraphicsImage.widgets = [{name:"load",text:"Load",type:"button"}]; - -GraphicsImage.supported_extensions = ["jpg","jpeg","png","gif"]; - -GraphicsImage.prototype.onAdded = function() -{ - if(this.properties["url"] != "" && this.img == null) - { - this.loadImage( this.properties["url"] ); - } -} - -GraphicsImage.prototype.onDrawBackground = function(ctx) -{ - if(this.flags.collapsed) - return; - if(this.img && this.size[0] > 5 && this.size[1] > 5) - ctx.drawImage(this.img, 0,0,this.size[0],this.size[1]); -} - - -GraphicsImage.prototype.onExecute = function() -{ - if(!this.img) - this.boxcolor = "#000"; - if(this.img && this.img.width) - this.setOutputData(0,this.img); - else - this.setOutputData(0,null); - if(this.img && this.img.dirty) - this.img.dirty = false; -} - -GraphicsImage.prototype.onPropertyChanged = function(name,value) -{ - this.properties[name] = value; - if (name == "url" && value != "") - this.loadImage(value); - - return true; -} - -GraphicsImage.prototype.loadImage = function( url, callback ) -{ - if(url == "") - { - this.img = null; - return; + this.addOutput("Texture","Texture"); + this.properties = { name:"", filter: true }; + this.size = [LGraphTexture.image_preview_size, LGraphTexture.image_preview_size]; } - this.img = document.createElement("img"); - - if(url.substr(0,4) == "http" && LiteGraph.proxy) - url = LiteGraph.proxy + url.substr( url.indexOf(":") + 3 ); - - this.img.src = url; - this.boxcolor = "#F95"; - var that = this; - this.img.onload = function() - { - if(callback) - callback(this); - that.trace("Image loaded, size: " + that.img.width + "x" + that.img.height ); - this.dirty = true; - that.boxcolor = "#9F9"; - that.setDirtyCanvas(true); - } -} - -GraphicsImage.prototype.onWidget = function(e,widget) -{ - if(widget.name == "load") - { - this.loadImage(this.properties["url"]); - } -} - -GraphicsImage.prototype.onDropFile = function(file) -{ - var that = this; - if(this._url) - URL.revokeObjectURL( this._url ); - this._url = URL.createObjectURL( file ); - this.properties.url = this._url; - this.loadImage( this._url, function(img){ - that.size[1] = (img.height / img.width) * that.size[0]; - }); -} - -LiteGraph.registerNodeType("graphics/image", GraphicsImage); - - - -function ColorPalette() -{ - this.addInput("f","number"); - this.addOutput("Color","color"); - this.properties = {colorA:"#444444",colorB:"#44AAFF",colorC:"#44FFAA",colorD:"#FFFFFF"}; - -} - -ColorPalette.title = "Palette"; -ColorPalette.desc = "Generates a color"; - -ColorPalette.prototype.onExecute = function() -{ - var c = []; - - if (this.properties.colorA != null) - c.push( hex2num( this.properties.colorA ) ); - if (this.properties.colorB != null) - c.push( hex2num( this.properties.colorB ) ); - if (this.properties.colorC != null) - c.push( hex2num( this.properties.colorC ) ); - if (this.properties.colorD != null) - c.push( hex2num( this.properties.colorD ) ); - - var f = this.getInputData(0); - if(f == null) f = 0.5; - if (f > 1.0) - f = 1.0; - else if (f < 0.0) - f = 0.0; - - if(c.length == 0) - return; - - var result = [0,0,0]; - if(f == 0) - result = c[0]; - else if(f == 1) - result = c[ c.length - 1]; - else - { - var pos = (c.length - 1)* f; - var c1 = c[ Math.floor(pos) ]; - var c2 = c[ Math.floor(pos)+1 ]; - var t = pos - Math.floor(pos); - result[0] = c1[0] * (1-t) + c2[0] * (t); - result[1] = c1[1] * (1-t) + c2[1] * (t); - result[2] = c1[2] * (1-t) + c2[2] * (t); - } - - /* - c[0] = 1.0 - Math.abs( Math.sin( 0.1 * reModular.getTime() * Math.PI) ); - c[1] = Math.abs( Math.sin( 0.07 * reModular.getTime() * Math.PI) ); - c[2] = Math.abs( Math.sin( 0.01 * reModular.getTime() * Math.PI) ); - */ - - for(var i in result) - result[i] /= 255; - - this.boxcolor = colorToString(result); - this.setOutputData(0, result); -} - - -LiteGraph.registerNodeType("color/palette", ColorPalette ); - - -function ImageFrame() -{ - this.addInput("","image,canvas"); - this.size = [200,200]; -} - -ImageFrame.title = "Frame"; -ImageFrame.desc = "Frame viewerew"; -ImageFrame.widgets = [{name:"resize",text:"Resize box",type:"button"},{name:"view",text:"View Image",type:"button"}]; - - -ImageFrame.prototype.onDrawBackground = function(ctx) -{ - if(this.frame && !this.flags.collapsed) - ctx.drawImage(this.frame, 0,0,this.size[0],this.size[1]); -} - -ImageFrame.prototype.onExecute = function() -{ - this.frame = this.getInputData(0); - this.setDirtyCanvas(true); -} - -ImageFrame.prototype.onWidget = function(e,widget) -{ - if(widget.name == "resize" && this.frame) - { - var width = this.frame.width; - var height = this.frame.height; - - if(!width && this.frame.videoWidth != null ) - { - width = this.frame.videoWidth; - height = this.frame.videoHeight; - } - - if(width && height) - this.size = [width, height]; - this.setDirtyCanvas(true,true); - } - else if(widget.name == "view") - this.show(); -} - -ImageFrame.prototype.show = function() -{ - //var str = this.canvas.toDataURL("image/png"); - if(showElement && this.frame) - showElement(this.frame); -} - - -LiteGraph.registerNodeType("graphics/frame", ImageFrame ); - - - - -function ImageFade() -{ - this.addInputs([["img1","image"],["img2","image"],["fade","number"]]); - this.addOutput("","image"); - this.properties = {fade:0.5,width:512,height:512}; -} - -ImageFade.title = "Image fade"; -ImageFade.desc = "Fades between images"; -ImageFade.widgets = [{name:"resizeA",text:"Resize to A",type:"button"},{name:"resizeB",text:"Resize to B",type:"button"}]; - -ImageFade.prototype.onAdded = function() -{ - this.createCanvas(); - var ctx = this.canvas.getContext("2d"); - ctx.fillStyle = "#000"; - ctx.fillRect(0,0,this.properties["width"],this.properties["height"]); -} - -ImageFade.prototype.createCanvas = function() -{ - this.canvas = document.createElement("canvas"); - this.canvas.width = this.properties["width"]; - this.canvas.height = this.properties["height"]; -} - -ImageFade.prototype.onExecute = function() -{ - var ctx = this.canvas.getContext("2d"); - this.canvas.width = this.canvas.width; - - var A = this.getInputData(0); - if (A != null) - { - ctx.drawImage(A,0,0,this.canvas.width, this.canvas.height); - } - - var fade = this.getInputData(2); - if(fade == null) - fade = this.properties["fade"]; - else - this.properties["fade"] = fade; - - ctx.globalAlpha = fade; - var B = this.getInputData(1); - if (B != null) - { - ctx.drawImage(B,0,0,this.canvas.width, this.canvas.height); - } - ctx.globalAlpha = 1.0; - - this.setOutputData(0,this.canvas); - this.setDirtyCanvas(true); -} - -LiteGraph.registerNodeType("graphics/imagefade", ImageFade); - - - -function ImageCrop() -{ - this.addInput("","image"); - this.addOutput("","image"); - this.properties = {width:256,height:256,x:0,y:0,scale:1.0 }; - this.size = [50,20]; -} - -ImageCrop.title = "Crop"; -ImageCrop.desc = "Crop Image"; - -ImageCrop.prototype.onAdded = function() -{ - this.createCanvas(); -} - -ImageCrop.prototype.createCanvas = function() -{ - this.canvas = document.createElement("canvas"); - this.canvas.width = this.properties["width"]; - this.canvas.height = this.properties["height"]; -} - -ImageCrop.prototype.onExecute = function() -{ - var input = this.getInputData(0); - if(!input) - return; - - if(input.width) - { - var ctx = this.canvas.getContext("2d"); - - ctx.drawImage(input, -this.properties["x"],-this.properties["y"], input.width * this.properties["scale"], input.height * this.properties["scale"]); - this.setOutputData(0,this.canvas); - } - else - this.setOutputData(0,null); -} - -ImageCrop.prototype.onDrawBackground = function(ctx) -{ - if(this.flags.collapsed) - return; - if(this.canvas) - ctx.drawImage( this.canvas, 0,0,this.canvas.width,this.canvas.height, 0,0, this.size[0], this.size[1] ); -} - -ImageCrop.prototype.onPropertyChanged = function(name,value) -{ - this.properties[name] = value; - - if(name == "scale") - { - this.properties[name] = parseFloat(value); - if(this.properties[name] == 0) - { - this.trace("Error in scale"); - this.properties[name] = 1.0; - } - } - else - this.properties[name] = parseInt(value); - - this.createCanvas(); - - return true; -} - -LiteGraph.registerNodeType("graphics/cropImage", ImageCrop ); - -//CANVAS stuff - -function CanvasNode() -{ - this.addInput("clear", LiteGraph.ACTION ); - this.addOutput("","canvas"); - this.properties = {width:512,height:512,autoclear:true}; - - this.canvas = document.createElement("canvas"); - this.ctx = this.canvas.getContext("2d"); -} - -CanvasNode.title = "Canvas"; -CanvasNode.desc = "Canvas to render stuff"; - -CanvasNode.prototype.onExecute = function() -{ - var canvas = this.canvas; - var w = (this.properties.width)|0; - var h = (this.properties.height)|0; - if( canvas.width != w ) - canvas.width = w; - if( canvas.height != h ) - canvas.height = h; - - if(this.properties.autoclear) - this.ctx.clearRect(0,0,canvas.width,canvas.height); - this.setOutputData(0,canvas); -} - -CanvasNode.prototype.onAction = function( action, param ) -{ - if(action == "clear") - this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height); -} - -LiteGraph.registerNodeType("graphics/canvas", CanvasNode ); - -function DrawImageNode() -{ - this.addInput("canvas", "canvas" ); - this.addInput("img", "image,canvas" ); - this.addInput("x", "number" ); - this.addInput("y", "number" ); - this.properties = {x:0,y:0,opacity:1}; -} - -DrawImageNode.title = "DrawImage"; -DrawImageNode.desc = "Draws image into a canvas"; - -DrawImageNode.prototype.onExecute = function() -{ - var canvas = this.getInputData(0); - if(!canvas) - return; - - var img = this.getInputOrProperty("img"); - if(!img) - return; - - var x = this.getInputOrProperty("x"); - var y = this.getInputOrProperty("y"); - var ctx = canvas.getContext("2d"); - ctx.drawImage( img, x, y ); -} - -LiteGraph.registerNodeType("graphics/drawImage", DrawImageNode ); - - -function DrawRectangleNode() -{ - this.addInput("canvas", "canvas" ); - this.addInput("x", "number" ); - this.addInput("y", "number" ); - this.addInput("w", "number" ); - this.addInput("h", "number" ); - this.properties = { x:0,y:0,w:10,h:10,color:"white",opacity:1 }; -} - -DrawRectangleNode.title = "DrawRectangle"; -DrawRectangleNode.desc = "Draws rectangle in canvas"; - -DrawRectangleNode.prototype.onExecute = function() -{ - var canvas = this.getInputData(0); - if(!canvas) - return; - - var x = this.getInputOrProperty("x"); - var y = this.getInputOrProperty("y"); - var w = this.getInputOrProperty("w"); - var h = this.getInputOrProperty("h"); - var ctx = canvas.getContext("2d"); - ctx.fillRect( x, y, w, h ); -} - -LiteGraph.registerNodeType("graphics/drawRectangle", DrawRectangleNode ); - - - -function ImageVideo() -{ - this.addInput("t","number"); - this.addOutputs([["frame","image"],["t","number"],["d","number"]]); - this.properties = { url:"", use_proxy: true }; -} - -ImageVideo.title = "Video"; -ImageVideo.desc = "Video playback"; -ImageVideo.widgets = [{name:"play",text:"PLAY",type:"minibutton"},{name:"stop",text:"STOP",type:"minibutton"},{name:"demo",text:"Demo video",type:"button"},{name:"mute",text:"Mute video",type:"button"}]; - -ImageVideo.prototype.onExecute = function() -{ - if(!this.properties.url) - return; - - if(this.properties.url != this._video_url) - this.loadVideo(this.properties.url); - - if(!this._video || this._video.width == 0) - return; - - var t = this.getInputData(0); - if(t && t >= 0 && t <= 1.0) - { - this._video.currentTime = t * this._video.duration; - this._video.pause(); - } - - this._video.dirty = true; - this.setOutputData(0,this._video); - this.setOutputData(1,this._video.currentTime); - this.setOutputData(2,this._video.duration); - this.setDirtyCanvas(true); -} - -ImageVideo.prototype.onStart = function() -{ - this.play(); -} - -ImageVideo.prototype.onStop = function() -{ - this.stop(); -} - -ImageVideo.prototype.loadVideo = function(url) -{ - this._video_url = url; - - if(this.properties.use_proxy && url.substr(0,4) == "http" && LiteGraph.proxy ) - url = LiteGraph.proxy + url.substr( url.indexOf(":") + 3 ); - - this._video = document.createElement("video"); - this._video.src = url; - this._video.type = "type=video/mp4"; - - this._video.muted = true; - this._video.autoplay = true; - - var that = this; - this._video.addEventListener("loadedmetadata",function(e) { - //onload - that.trace("Duration: " + this.duration + " seconds"); - that.trace("Size: " + this.videoWidth + "," + this.videoHeight); - that.setDirtyCanvas(true); - this.width = this.videoWidth; - this.height = this.videoHeight; - }); - this._video.addEventListener("progress",function(e) { - //onload - //that.trace("loading..."); - }); - this._video.addEventListener("error",function(e) { - console.log("Error loading video: " + this.src); - that.trace("Error loading video: " + this.src); - if (this.error) { - switch (this.error.code) { - case this.error.MEDIA_ERR_ABORTED: - that.trace("You stopped the video."); - break; - case this.error.MEDIA_ERR_NETWORK: - that.trace("Network error - please try again later."); - break; - case this.error.MEDIA_ERR_DECODE: - that.trace("Video is broken.."); - break; - case this.error.MEDIA_ERR_SRC_NOT_SUPPORTED: - that.trace("Sorry, your browser can't play this video."); - break; - } - } - }); - - this._video.addEventListener("ended",function(e) { - that.trace("Ended."); - this.play(); //loop - }); - - //document.body.appendChild(this.video); -} - -ImageVideo.prototype.onPropertyChanged = function(name,value) -{ - this.properties[name] = value; - if (name == "url" && value != "") - this.loadVideo(value); - - return true; -} - -ImageVideo.prototype.play = function() -{ - if(this._video) - this._video.play(); -} - -ImageVideo.prototype.playPause = function() -{ - if(!this._video) - return; - if(this._video.paused) - this.play(); - else - this.pause(); -} - -ImageVideo.prototype.stop = function() -{ - if(!this._video) - return; - this._video.pause(); - this._video.currentTime = 0; -} - -ImageVideo.prototype.pause = function() -{ - if(!this._video) - return; - this.trace("Video paused"); - this._video.pause(); -} - -ImageVideo.prototype.onWidget = function(e,widget) -{ - /* - if(widget.name == "demo") - { - this.loadVideo(); - } - else if(widget.name == "play") - { - if(this._video) - this.playPause(); - } - if(widget.name == "stop") - { - this.stop(); - } - else if(widget.name == "mute") - { - if(this._video) - this._video.muted = !this._video.muted; - } - */ -} - -LiteGraph.registerNodeType("graphics/video", ImageVideo ); - - -// Texture Webcam ***************************************** -function ImageWebcam() -{ - this.addOutput("Webcam","image"); - this.properties = { facingMode: "user" }; - this.boxcolor = "black"; - this.frame = 0; -} - -ImageWebcam.title = "Webcam"; -ImageWebcam.desc = "Webcam image"; - - -ImageWebcam.prototype.openStream = function() -{ - if (!navigator.getUserMedia) { - //console.log('getUserMedia() is not supported in your browser, use chrome and enable WebRTC from about://flags'); - return; - } - - this._waiting_confirmation = true; - - // Not showing vendor prefixes. - var constraints = { audio: false, video: { facingMode: this.properties.facingMode } }; - navigator.mediaDevices.getUserMedia( constraints ).then( this.streamReady.bind(this) ).catch( onFailSoHard ); - - var that = this; - function onFailSoHard(e) { - console.log('Webcam rejected', e); - that._webcam_stream = false; - that.boxcolor = "red"; - that.trigger("stream_error"); + global.LGraphTexture = LGraphTexture; + + LGraphTexture.title = "Texture"; + LGraphTexture.desc = "Texture"; + LGraphTexture.widgets_info = {"name": { widget:"texture"}, "filter": { widget:"checkbox"} }; + + //REPLACE THIS TO INTEGRATE WITH YOUR FRAMEWORK + LGraphTexture.loadTextureCallback = null; //function in charge of loading textures when not present in the container + LGraphTexture.image_preview_size = 256; + + //flags to choose output texture type + LGraphTexture.PASS_THROUGH = 1; //do not apply FX + LGraphTexture.COPY = 2; //create new texture with the same properties as the origin texture + LGraphTexture.LOW = 3; //create new texture with low precision (byte) + LGraphTexture.HIGH = 4; //create new texture with high precision (half-float) + LGraphTexture.REUSE = 5; //reuse input texture + LGraphTexture.DEFAULT = 2; + + LGraphTexture.MODE_VALUES = { + "pass through": LGraphTexture.PASS_THROUGH, + "copy": LGraphTexture.COPY, + "low": LGraphTexture.LOW, + "high": LGraphTexture.HIGH, + "reuse": LGraphTexture.REUSE, + "default": LGraphTexture.DEFAULT }; -} -ImageWebcam.prototype.closeStream = function() -{ - if(this._webcam_stream) + //returns the container where all the loaded textures are stored (overwrite if you have a Resources Manager) + LGraphTexture.getTexturesContainer = function() { + return gl.textures; + } + + //process the loading of a texture (overwrite it if you have a Resources Manager) + LGraphTexture.loadTexture = function(name, options) + { + options = options || {}; + var url = name; + if(url.substr(0,7) == "http://") + { + if(LiteGraph.proxy) //proxy external files + url = LiteGraph.proxy + url.substr(7); + } + + var container = LGraphTexture.getTexturesContainer(); + var tex = container[ name ] = GL.Texture.fromURL(url, options); + return tex; + } + + LGraphTexture.getTexture = function(name) + { + var container = this.getTexturesContainer(); + + if(!container) + throw("Cannot load texture, container of textures not found"); + + var tex = container[ name ]; + if(!tex && name && name[0] != ":") + return this.loadTexture(name); + + return tex; + } + + //used to compute the appropiate output texture + LGraphTexture.getTargetTexture = function( origin, target, mode ) + { + if(!origin) + throw("LGraphTexture.getTargetTexture expects a reference texture"); + + var tex_type = null; + + switch(mode) + { + case LGraphTexture.LOW: tex_type = gl.UNSIGNED_BYTE; break; + case LGraphTexture.HIGH: tex_type = gl.HIGH_PRECISION_FORMAT; break; + case LGraphTexture.REUSE: return origin; break; + case LGraphTexture.COPY: + default: tex_type = origin ? origin.type : gl.UNSIGNED_BYTE; break; + } + + if(!target || target.width != origin.width || target.height != origin.height || target.type != tex_type ) + target = new GL.Texture( origin.width, origin.height, { type: tex_type, format: gl.RGBA, filter: gl.LINEAR }); + + return target; + } + + + LGraphTexture.getTextureType = function( precision, ref_texture ) + { + var type = ref_texture ? ref_texture.type : gl.UNSIGNED_BYTE; + switch( precision ) + { + case LGraphTexture.HIGH: type = gl.HIGH_PRECISION_FORMAT; break; + case LGraphTexture.LOW: type = gl.UNSIGNED_BYTE; break; + //no default + } + return type; + } + + LGraphTexture.getNoiseTexture = function() + { + if(this._noise_texture) + return this._noise_texture; + + var noise = new Uint8Array(512*512*4); + for(var i = 0; i < 512*512*4; ++i) + noise[i] = Math.random() * 255; + + var texture = GL.Texture.fromMemory(512,512,noise,{ format: gl.RGBA, wrap: gl.REPEAT, filter: gl.NEAREST }); + this._noise_texture = texture; + return texture; + } + + LGraphTexture.prototype.onDropFile = function(data, filename, file) + { + if(!data) + { + this._drop_texture = null; + this.properties.name = ""; + } + else + { + var texture = null; + if( typeof(data) == "string" ) + texture = GL.Texture.fromURL( data ); + else if( filename.toLowerCase().indexOf(".dds") != -1 ) + texture = GL.Texture.fromDDSInMemory(data); + else + { + var blob = new Blob([file]); + var url = URL.createObjectURL(blob); + texture = GL.Texture.fromURL( url ); + } + + this._drop_texture = texture; + this.properties.name = filename; + } + } + + LGraphTexture.prototype.getExtraMenuOptions = function(graphcanvas) + { + var that = this; + if(!this._drop_texture) + return; + return [ {content:"Clear", callback: + function() { + that._drop_texture = null; + that.properties.name = ""; + } + }]; + } + + LGraphTexture.prototype.onExecute = function() + { + var tex = null; + if(this.isOutputConnected(1)) + tex = this.getInputData(0); + + if(!tex && this._drop_texture) + tex = this._drop_texture; + + if(!tex && this.properties.name) + tex = LGraphTexture.getTexture( this.properties.name ); + + if(!tex) + return; + + this._last_tex = tex; + + if(this.properties.filter === false) + tex.setParameter( gl.TEXTURE_MAG_FILTER, gl.NEAREST ); + else + tex.setParameter( gl.TEXTURE_MAG_FILTER, gl.LINEAR ); + + this.setOutputData(0, tex); + + for(var i = 1; i < this.outputs.length; i++) + { + var output = this.outputs[i]; + if(!output) + continue; + var v = null; + if(output.name == "width") + v = tex.width; + else if(output.name == "height") + v = tex.height; + else if(output.name == "aspect") + v = tex.width / tex.height; + this.setOutputData(i, v); + } + } + + LGraphTexture.prototype.onResourceRenamed = function(old_name,new_name) + { + if(this.properties.name == old_name) + this.properties.name = new_name; + } + + LGraphTexture.prototype.onDrawBackground = function(ctx) + { + if( this.flags.collapsed || this.size[1] <= 20 ) + return; + + if( this._drop_texture && ctx.webgl ) + { + ctx.drawImage( this._drop_texture, 0,0,this.size[0],this.size[1]); + //this._drop_texture.renderQuad(this.pos[0],this.pos[1],this.size[0],this.size[1]); + return; + } + + + //Different texture? then get it from the GPU + if(this._last_preview_tex != this._last_tex) + { + if(ctx.webgl) + { + this._canvas = this._last_tex; + } + else + { + var tex_canvas = LGraphTexture.generateLowResTexturePreview(this._last_tex); + if(!tex_canvas) + return; + + this._last_preview_tex = this._last_tex; + this._canvas = cloneCanvas(tex_canvas); + } + } + + if(!this._canvas) + return; + + //render to graph canvas + ctx.save(); + if(!ctx.webgl) //reverse image + { + ctx.translate(0,this.size[1]); + ctx.scale(1,-1); + } + ctx.drawImage(this._canvas,0,0,this.size[0],this.size[1]); + ctx.restore(); + } + + + //very slow, used at your own risk + LGraphTexture.generateLowResTexturePreview = function(tex) + { + if(!tex) + return null; + + var size = LGraphTexture.image_preview_size; + var temp_tex = tex; + + if(tex.format == gl.DEPTH_COMPONENT) + return null; //cannot generate from depth + + //Generate low-level version in the GPU to speed up + if(tex.width > size || tex.height > size) + { + temp_tex = this._preview_temp_tex; + if(!this._preview_temp_tex) + { + temp_tex = new GL.Texture(size,size, { minFilter: gl.NEAREST }); + this._preview_temp_tex = temp_tex; + } + + //copy + tex.copyTo(temp_tex); + tex = temp_tex; + } + + //create intermediate canvas with lowquality version + var tex_canvas = this._preview_canvas; + if(!tex_canvas) + { + tex_canvas = createCanvas(size,size); + this._preview_canvas = tex_canvas; + } + + if(temp_tex) + temp_tex.toCanvas(tex_canvas); + return tex_canvas; + } + + LGraphTexture.prototype.getResources = function(res) + { + res[ this.properties.name ] = GL.Texture; + return res; + } + + LGraphTexture.prototype.onGetInputs = function() + { + return [["in","Texture"]]; + } + + + LGraphTexture.prototype.onGetOutputs = function() + { + return [["width","number"],["height","number"],["aspect","number"]]; + } + + LiteGraph.registerNodeType("texture/texture", LGraphTexture ); + + //************************** + function LGraphTexturePreview() + { + this.addInput("Texture","Texture"); + this.properties = { flipY: false }; + this.size = [LGraphTexture.image_preview_size, LGraphTexture.image_preview_size]; + } + + LGraphTexturePreview.title = "Preview"; + LGraphTexturePreview.desc = "Show a texture in the graph canvas"; + LGraphTexturePreview.allow_preview = false; + + LGraphTexturePreview.prototype.onDrawBackground = function(ctx) + { + if(this.flags.collapsed) + return; + + if(!ctx.webgl && !LGraphTexturePreview.allow_preview) + return; //not working well + + var tex = this.getInputData(0); + if(!tex) + return; + + var tex_canvas = null; + + if(!tex.handle && ctx.webgl) + tex_canvas = tex; + else + tex_canvas = LGraphTexture.generateLowResTexturePreview(tex); + + //render to graph canvas + ctx.save(); + if(this.properties.flipY) + { + ctx.translate(0,this.size[1]); + ctx.scale(1,-1); + } + ctx.drawImage(tex_canvas,0,0,this.size[0],this.size[1]); + ctx.restore(); + } + + LiteGraph.registerNodeType("texture/preview", LGraphTexturePreview ); + + //************************************** + + function LGraphTextureSave() + { + this.addInput("Texture","Texture"); + this.addOutput("","Texture"); + this.properties = {name:""}; + } + + LGraphTextureSave.title = "Save"; + LGraphTextureSave.desc = "Save a texture in the repository"; + + LGraphTextureSave.prototype.onExecute = function() + { + var tex = this.getInputData(0); + if(!tex) + return; + + if(this.properties.name) + { + //for cases where we want to perform something when storing it + if( LGraphTexture.storeTexture ) + LGraphTexture.storeTexture( this.properties.name, tex ); + else + { + var container = LGraphTexture.getTexturesContainer(); + container[ this.properties.name ] = tex; + } + } + + this.setOutputData(0, tex); + } + + LiteGraph.registerNodeType("texture/save", LGraphTextureSave ); + + //**************************************************** + + function LGraphTextureOperation() + { + this.addInput("Texture","Texture"); + this.addInput("TextureB","Texture"); + this.addInput("value","number"); + this.addOutput("Texture","Texture"); + this.help = "
pixelcode must be vec3
\ +uvcode must be vec2, is optional
\ +uv: tex. coords
color: texture
colorB: textureB
time: scene time
value: input value
"; + + this.properties = {value:1, uvcode:"", pixelcode:"color + colorB * value", precision: LGraphTexture.DEFAULT }; + } + + LGraphTextureOperation.widgets_info = { + "uvcode": { widget:"textarea", height: 100 }, + "pixelcode": { widget:"textarea", height: 100 }, + "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } + }; + + LGraphTextureOperation.title = "Operation"; + LGraphTextureOperation.desc = "Texture shader operation"; + + LGraphTextureOperation.prototype.getExtraMenuOptions = function(graphcanvas) + { + var that = this; + var txt = !that.properties.show ? "Show Texture" : "Hide Texture"; + return [ {content: txt, callback: + function() { + that.properties.show = !that.properties.show; + } + }]; + } + + LGraphTextureOperation.prototype.onDrawBackground = function(ctx) + { + if(this.flags.collapsed || this.size[1] <= 20 || !this.properties.show) + return; + + if(!this._tex) + return; + + //only works if using a webgl renderer + if(this._tex.gl != ctx) + return; + + //render to graph canvas + ctx.save(); + ctx.drawImage(this._tex, 0, 0, this.size[0], this.size[1]); + ctx.restore(); + } + + LGraphTextureOperation.prototype.onExecute = function() + { + var tex = this.getInputData(0); + + if(!this.isOutputConnected(0)) + return; //saves work + + if(this.properties.precision === LGraphTexture.PASS_THROUGH) + { + this.setOutputData(0, tex); + return; + } + + var texB = this.getInputData(1); + + if(!this.properties.uvcode && !this.properties.pixelcode) + return; + + var width = 512; + var height = 512; + if(tex) + { + width = tex.width; + height = tex.height; + } + else if (texB) + { + width = texB.width; + height = texB.height; + } + + var type = LGraphTexture.getTextureType( this.properties.precision, tex ); + + if(!tex && !this._tex ) + this._tex = new GL.Texture( width, height, { type: type, format: gl.RGBA, filter: gl.LINEAR }); + else + this._tex = LGraphTexture.getTargetTexture( tex || this._tex, this._tex, this.properties.precision ); + + var uvcode = ""; + if(this.properties.uvcode) + { + uvcode = "uv = " + this.properties.uvcode; + if(this.properties.uvcode.indexOf(";") != -1) //there are line breaks, means multiline code + uvcode = this.properties.uvcode; + } + + var pixelcode = ""; + if(this.properties.pixelcode) + { + pixelcode = "result = " + this.properties.pixelcode; + if(this.properties.pixelcode.indexOf(";") != -1) //there are line breaks, means multiline code + pixelcode = this.properties.pixelcode; + } + + var shader = this._shader; + + if(!shader || this._shader_code != (uvcode + "|" + pixelcode) ) + { + try + { + this._shader = new GL.Shader(Shader.SCREEN_VERTEX_SHADER, LGraphTextureOperation.pixel_shader, { UV_CODE: uvcode, PIXEL_CODE: pixelcode }); + this.boxcolor = "#00FF00"; + } + catch (err) + { + console.log("Error compiling shader: ", err); + this.boxcolor = "#FF0000"; + return; + } + this.boxcolor = "#FF0000"; + + this._shader_code = (uvcode + "|" + pixelcode); + shader = this._shader; + } + + if(!shader) + { + this.boxcolor = "red"; + return; + } + else + this.boxcolor = "green"; + + var value = this.getInputData(2); + if(value != null) + this.properties.value = value; + else + value = parseFloat( this.properties.value ); + + var time = this.graph.getTime(); + + this._tex.drawTo(function() { + gl.disable( gl.DEPTH_TEST ); + gl.disable( gl.CULL_FACE ); + gl.disable( gl.BLEND ); + if(tex) tex.bind(0); + if(texB) texB.bind(1); + var mesh = Mesh.getScreenQuad(); + shader.uniforms({u_texture:0, u_textureB:1, value: value, texSize:[width,height], time: time}).draw(mesh); + }); + + this.setOutputData(0, this._tex); + } + + LGraphTextureOperation.pixel_shader = "precision highp float;\n\ + \n\ + uniform sampler2D u_texture;\n\ + uniform sampler2D u_textureB;\n\ + varying vec2 v_coord;\n\ + uniform vec2 texSize;\n\ + uniform float time;\n\ + uniform float value;\n\ + \n\ + void main() {\n\ + vec2 uv = v_coord;\n\ + UV_CODE;\n\ + vec4 color4 = texture2D(u_texture, uv);\n\ + vec3 color = color4.rgb;\n\ + vec4 color4B = texture2D(u_textureB, uv);\n\ + vec3 colorB = color4B.rgb;\n\ + vec3 result = color;\n\ + float alpha = 1.0;\n\ + PIXEL_CODE;\n\ + gl_FragColor = vec4(result, alpha);\n\ + }\n\ + "; + + LiteGraph.registerNodeType("texture/operation", LGraphTextureOperation ); + + //**************************************************** + + function LGraphTextureShader() + { + this.addOutput("out","Texture"); + this.properties = {code:"", width: 512, height: 512, precision: LGraphTexture.DEFAULT }; + + this.properties.code = "\nvoid main() {\n vec2 uv = v_coord;\n vec3 color = vec3(0.0);\n//your code here\n\ngl_FragColor = vec4(color, 1.0);\n}\n"; + this._uniforms = { in_texture:0, texSize: vec2.create(), time: 0 }; + } + + LGraphTextureShader.title = "Shader"; + LGraphTextureShader.desc = "Texture shader"; + LGraphTextureShader.widgets_info = { + "code": { type:"code" }, + "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } + }; + + LGraphTextureShader.prototype.onPropertyChanged = function(name, value) + { + if(name != "code") + return; + + var shader = this.getShader(); + if(!shader) + return; + + //update connections + var uniforms = shader.uniformInfo; + + //remove deprecated slots + if(this.inputs) + { + var already = {}; + for(var i = 0; i < this.inputs.length; ++i) + { + var info = this.getInputInfo(i); + if(!info) + continue; + + if( uniforms[ info.name ] && !already[ info.name ] ) + { + already[ info.name ] = true; + continue; + } + this.removeInput(i); + i--; + } + } + + //update existing ones + for(var i in uniforms) + { + var info = shader.uniformInfo[i]; + if(info.loc === null) + continue; //is an attribute, not a uniform + if(i == "time") //default one + continue; + + var type = "number"; + if( this._shader.samplers[i] ) + type = "texture"; + else + { + switch(info.size) + { + case 1: type = "number"; break; + case 2: type = "vec2"; break; + case 3: type = "vec3"; break; + case 4: type = "vec4"; break; + case 9: type = "mat3"; break; + case 16: type = "mat4"; break; + default: continue; + } + } + + var slot = this.findInputSlot(i); + if(slot == -1) + { + this.addInput(i,type); + continue; + } + + var input_info = this.getInputInfo(slot); + if(!input_info) + this.addInput(i,type); + else + { + if(input_info.type == type) + continue; + this.removeInput(slot,type); + this.addInput(i,type); + } + } + } + + LGraphTextureShader.prototype.getShader = function() + { + //replug + if(this._shader && this._shader_code == this.properties.code) + return this._shader; + + this._shader_code = this.properties.code; + this._shader = new GL.Shader(Shader.SCREEN_VERTEX_SHADER, LGraphTextureShader.pixel_shader + this.properties.code ); + if(!this._shader) { + this.boxcolor = "red"; + return null; + } + else + this.boxcolor = "green"; + return this._shader; + } + + LGraphTextureShader.prototype.onExecute = function() + { + if(!this.isOutputConnected(0)) + return; //saves work + + var shader = this.getShader(); + if(!shader) + return; + + var tex_slot = 0; + var in_tex = null; + + //set uniforms + for(var i = 0; i < this.inputs.length; ++i) + { + var info = this.getInputInfo(i); + var data = this.getInputData(i); + if(data == null) + continue; + + if(data.constructor === GL.Texture) + { + data.bind(tex_slot); + if(!in_tex) + in_tex = data; + data = tex_slot; + tex_slot++; + } + shader.setUniform( info.name, data ); //data is tex_slot + } + + var uniforms = this._uniforms; + var type = LGraphTexture.getTextureType( this.properties.precision, in_tex ); + + //render to texture + var w = this.properties.width|0; + var h = this.properties.height|0; + if(w == 0) + w = in_tex ? in_tex.width : gl.canvas.width; + if(h == 0) + h = in_tex ? in_tex.height : gl.canvas.height; + uniforms.texSize[0] = w; + uniforms.texSize[1] = h; + uniforms.time = this.graph.getTime(); + + if(!this._tex || this._tex.type != type || this._tex.width != w || this._tex.height != h ) + this._tex = new GL.Texture( w, h, { type: type, format: gl.RGBA, filter: gl.LINEAR }); + var tex = this._tex; + tex.drawTo(function() { + shader.uniforms( uniforms ).draw( GL.Mesh.getScreenQuad() ); + }); + + this.setOutputData( 0, this._tex ); + } + + LGraphTextureShader.pixel_shader = "precision highp float;\n\ + \n\ + varying vec2 v_coord;\n\ + uniform float time;\n\ + "; + + LiteGraph.registerNodeType("texture/shader", LGraphTextureShader ); + + // Texture Scale Offset + + function LGraphTextureScaleOffset() + { + this.addInput("in","Texture"); + this.addInput("scale","vec2"); + this.addInput("offset","vec2"); + this.addOutput("out","Texture"); + this.properties = { offset: vec2.fromValues(0,0), scale: vec2.fromValues(1,1), precision: LGraphTexture.DEFAULT }; + } + + LGraphTextureScaleOffset.widgets_info = { + "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } + }; + + LGraphTextureScaleOffset.title = "Scale/Offset"; + LGraphTextureScaleOffset.desc = "Applies an scaling and offseting"; + + LGraphTextureScaleOffset.prototype.onExecute = function() + { + var tex = this.getInputData(0); + + if(!this.isOutputConnected(0) || !tex) + return; //saves work + + if(this.properties.precision === LGraphTexture.PASS_THROUGH) + { + this.setOutputData(0, tex); + return; + } + + var width = tex.width; + var height = tex.height; + var type = this.precision === LGraphTexture.LOW ? gl.UNSIGNED_BYTE : gl.HIGH_PRECISION_FORMAT; + if (this.precision === LGraphTexture.DEFAULT) + type = tex.type; + + if(!this._tex || this._tex.width != width || this._tex.height != height || this._tex.type != type ) + this._tex = new GL.Texture( width, height, { type: type, format: gl.RGBA, filter: gl.LINEAR }); + + var shader = this._shader; + + if(!shader) + shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureScaleOffset.pixel_shader ); + + var scale = this.getInputData(1); + if(scale) + { + this.properties.scale[0] = scale[0]; + this.properties.scale[1] = scale[1]; + } + else + scale = this.properties.scale; + + var offset = this.getInputData(2); + if(offset) + { + this.properties.offset[0] = offset[0]; + this.properties.offset[1] = offset[1]; + } + else + offset = this.properties.offset; + + this._tex.drawTo(function() { + gl.disable( gl.DEPTH_TEST ); + gl.disable( gl.CULL_FACE ); + gl.disable( gl.BLEND ); + tex.bind(0); + var mesh = Mesh.getScreenQuad(); + shader.uniforms({u_texture:0, u_scale: scale, u_offset: offset}).draw( mesh ); + }); + + this.setOutputData( 0, this._tex ); + } + + LGraphTextureScaleOffset.pixel_shader = "precision highp float;\n\ + \n\ + uniform sampler2D u_texture;\n\ + uniform sampler2D u_textureB;\n\ + varying vec2 v_coord;\n\ + uniform vec2 u_scale;\n\ + uniform vec2 u_offset;\n\ + \n\ + void main() {\n\ + vec2 uv = v_coord;\n\ + uv = uv / u_scale - u_offset;\n\ + gl_FragColor = texture2D(u_texture, uv);\n\ + }\n\ + "; + + LiteGraph.registerNodeType("texture/scaleOffset", LGraphTextureScaleOffset ); + + + + // Warp (distort a texture) ************************* + + function LGraphTextureWarp() + { + this.addInput("in","Texture"); + this.addInput("warp","Texture"); + this.addInput("factor","number"); + this.addOutput("out","Texture"); + this.properties = { factor: 0.01, precision: LGraphTexture.DEFAULT }; + } + + LGraphTextureWarp.widgets_info = { + "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } + }; + + LGraphTextureWarp.title = "Warp"; + LGraphTextureWarp.desc = "Texture warp operation"; + + LGraphTextureWarp.prototype.onExecute = function() + { + var tex = this.getInputData(0); + + if(!this.isOutputConnected(0)) + return; //saves work + + if(this.properties.precision === LGraphTexture.PASS_THROUGH) + { + this.setOutputData(0, tex); + return; + } + + var texB = this.getInputData(1); + + var width = 512; + var height = 512; + var type = gl.UNSIGNED_BYTE; + if(tex) + { + width = tex.width; + height = tex.height; + type = tex.type; + } + else if (texB) + { + width = texB.width; + height = texB.height; + type = texB.type; + } + + if(!tex && !this._tex ) + this._tex = new GL.Texture( width, height, { type: this.precision === LGraphTexture.LOW ? gl.UNSIGNED_BYTE : gl.HIGH_PRECISION_FORMAT, format: gl.RGBA, filter: gl.LINEAR }); + else + this._tex = LGraphTexture.getTargetTexture( tex || this._tex, this._tex, this.properties.precision ); + + var shader = this._shader; + + if(!shader) + shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureWarp.pixel_shader ); + + var factor = this.getInputData(2); + if(factor != null) + this.properties.factor = factor; + else + factor = parseFloat( this.properties.factor ); + + this._tex.drawTo(function() { + gl.disable( gl.DEPTH_TEST ); + gl.disable( gl.CULL_FACE ); + gl.disable( gl.BLEND ); + if(tex) tex.bind(0); + if(texB) texB.bind(1); + var mesh = Mesh.getScreenQuad(); + shader.uniforms({u_texture:0, u_textureB:1, u_factor: factor }).draw( mesh ); + }); + + this.setOutputData(0, this._tex); + } + + LGraphTextureWarp.pixel_shader = "precision highp float;\n\ + \n\ + uniform sampler2D u_texture;\n\ + uniform sampler2D u_textureB;\n\ + varying vec2 v_coord;\n\ + uniform float u_factor;\n\ + \n\ + void main() {\n\ + vec2 uv = v_coord;\n\ + uv += ( texture2D(u_textureB, uv).rg - vec2(0.5)) * u_factor;\n\ + gl_FragColor = texture2D(u_texture, uv);\n\ + }\n\ + "; + + LiteGraph.registerNodeType("texture/warp", LGraphTextureWarp ); + + //**************************************************** + + // Texture to Viewport ***************************************** + function LGraphTextureToViewport() + { + this.addInput("Texture","Texture"); + this.properties = { additive: false, antialiasing: false, filter: true, disable_alpha: false, gamma: 1.0 }; + this.size[0] = 130; + } + + LGraphTextureToViewport.title = "to Viewport"; + LGraphTextureToViewport.desc = "Texture to viewport"; + + LGraphTextureToViewport.prototype.onExecute = function() + { + var tex = this.getInputData(0); + if(!tex) + return; + + if(this.properties.disable_alpha) + gl.disable( gl.BLEND ); + else + { + gl.enable( gl.BLEND ); + if(this.properties.additive) + gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); + else + gl.blendFunc( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA ); + } + + gl.disable( gl.DEPTH_TEST ); + var gamma = this.properties.gamma || 1.0; + if( this.isInputConnected(1) ) + gamma = this.getInputData(1); + + tex.setParameter( gl.TEXTURE_MAG_FILTER, this.properties.filter ? gl.LINEAR : gl.NEAREST ); + + if(this.properties.antialiasing) + { + if(!LGraphTextureToViewport._shader) + LGraphTextureToViewport._shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureToViewport.aa_pixel_shader ); + + var viewport = gl.getViewport(); //gl.getParameter(gl.VIEWPORT); + var mesh = Mesh.getScreenQuad(); + tex.bind(0); + LGraphTextureToViewport._shader.uniforms({u_texture:0, uViewportSize:[tex.width,tex.height], u_igamma: 1 / gamma, inverseVP: [1/tex.width,1/tex.height] }).draw(mesh); + } + else + { + if(gamma != 1.0) + { + if(!LGraphTextureToViewport._gamma_shader) + LGraphTextureToViewport._gamma_shader = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureToViewport.gamma_pixel_shader ); + tex.toViewport(LGraphTextureToViewport._gamma_shader, { u_texture:0, u_igamma: 1 / gamma }); + } + else + tex.toViewport(); + } + } + + LGraphTextureToViewport.prototype.onGetInputs = function() + { + return [["gamma","number"]]; + } + + LGraphTextureToViewport.aa_pixel_shader = "precision highp float;\n\ + precision highp float;\n\ + varying vec2 v_coord;\n\ + uniform sampler2D u_texture;\n\ + uniform vec2 uViewportSize;\n\ + uniform vec2 inverseVP;\n\ + uniform float u_igamma;\n\ + #define FXAA_REDUCE_MIN (1.0/ 128.0)\n\ + #define FXAA_REDUCE_MUL (1.0 / 8.0)\n\ + #define FXAA_SPAN_MAX 8.0\n\ + \n\ + /* from mitsuhiko/webgl-meincraft based on the code on geeks3d.com */\n\ + vec4 applyFXAA(sampler2D tex, vec2 fragCoord)\n\ + {\n\ + vec4 color = vec4(0.0);\n\ + /*vec2 inverseVP = vec2(1.0 / uViewportSize.x, 1.0 / uViewportSize.y);*/\n\ + vec3 rgbNW = texture2D(tex, (fragCoord + vec2(-1.0, -1.0)) * inverseVP).xyz;\n\ + vec3 rgbNE = texture2D(tex, (fragCoord + vec2(1.0, -1.0)) * inverseVP).xyz;\n\ + vec3 rgbSW = texture2D(tex, (fragCoord + vec2(-1.0, 1.0)) * inverseVP).xyz;\n\ + vec3 rgbSE = texture2D(tex, (fragCoord + vec2(1.0, 1.0)) * inverseVP).xyz;\n\ + vec3 rgbM = texture2D(tex, fragCoord * inverseVP).xyz;\n\ + vec3 luma = vec3(0.299, 0.587, 0.114);\n\ + float lumaNW = dot(rgbNW, luma);\n\ + float lumaNE = dot(rgbNE, luma);\n\ + float lumaSW = dot(rgbSW, luma);\n\ + float lumaSE = dot(rgbSE, luma);\n\ + float lumaM = dot(rgbM, luma);\n\ + float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n\ + float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\ + \n\ + vec2 dir;\n\ + dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n\ + dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\ + \n\ + float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\ + \n\ + float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n\ + dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX), max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX), dir * rcpDirMin)) * inverseVP;\n\ + \n\ + vec3 rgbA = 0.5 * (texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz + \n\ + texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n\ + vec3 rgbB = rgbA * 0.5 + 0.25 * (texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz + \n\ + texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\ + \n\ + //return vec4(rgbA,1.0);\n\ + float lumaB = dot(rgbB, luma);\n\ + if ((lumaB < lumaMin) || (lumaB > lumaMax))\n\ + color = vec4(rgbA, 1.0);\n\ + else\n\ + color = vec4(rgbB, 1.0);\n\ + if(u_igamma != 1.0)\n\ + color.xyz = pow( color.xyz, vec3(u_igamma) );\n\ + return color;\n\ + }\n\ + \n\ + void main() {\n\ + gl_FragColor = applyFXAA( u_texture, v_coord * uViewportSize) ;\n\ + }\n\ + "; + + LGraphTextureToViewport.gamma_pixel_shader = "precision highp float;\n\ + precision highp float;\n\ + varying vec2 v_coord;\n\ + uniform sampler2D u_texture;\n\ + uniform float u_igamma;\n\ + void main() {\n\ + vec4 color = texture2D( u_texture, v_coord);\n\ + color.xyz = pow(color.xyz, vec3(u_igamma) );\n\ + gl_FragColor = color;\n\ + }\n\ + "; + + + LiteGraph.registerNodeType("texture/toviewport", LGraphTextureToViewport ); + + + // Texture Copy ***************************************** + function LGraphTextureCopy() + { + this.addInput("Texture","Texture"); + this.addOutput("","Texture"); + this.properties = { size: 0, generate_mipmaps: false, precision: LGraphTexture.DEFAULT }; + } + + LGraphTextureCopy.title = "Copy"; + LGraphTextureCopy.desc = "Copy Texture"; + LGraphTextureCopy.widgets_info = { + size: { widget:"combo", values:[0,32,64,128,256,512,1024,2048]}, + precision: { widget:"combo", values: LGraphTexture.MODE_VALUES } + }; + + LGraphTextureCopy.prototype.onExecute = function() + { + var tex = this.getInputData(0); + if(!tex && !this._temp_texture) + return; + + if(!this.isOutputConnected(0)) + return; //saves work + + //copy the texture + if(tex) + { + var width = tex.width; + var height = tex.height; + + if(this.properties.size != 0) + { + width = this.properties.size; + height = this.properties.size; + } + + var temp = this._temp_texture; + + var type = tex.type; + if(this.properties.precision === LGraphTexture.LOW) + type = gl.UNSIGNED_BYTE; + else if(this.properties.precision === LGraphTexture.HIGH) + type = gl.HIGH_PRECISION_FORMAT; + + if(!temp || temp.width != width || temp.height != height || temp.type != type ) + { + var minFilter = gl.LINEAR; + if( this.properties.generate_mipmaps && isPowerOfTwo(width) && isPowerOfTwo(height) ) + minFilter = gl.LINEAR_MIPMAP_LINEAR; + this._temp_texture = new GL.Texture( width, height, { type: type, format: gl.RGBA, minFilter: minFilter, magFilter: gl.LINEAR }); + } + tex.copyTo(this._temp_texture); + + if(this.properties.generate_mipmaps) + { + this._temp_texture.bind(0); + gl.generateMipmap(this._temp_texture.texture_type); + this._temp_texture.unbind(0); + } + } + + + this.setOutputData(0,this._temp_texture); + } + + LiteGraph.registerNodeType("texture/copy", LGraphTextureCopy ); + + + // Texture Downsample ***************************************** + function LGraphTextureDownsample() + { + this.addInput("Texture","Texture"); + this.addOutput("","Texture"); + this.properties = { iterations: 1, generate_mipmaps: false, precision: LGraphTexture.DEFAULT }; + } + + LGraphTextureDownsample.title = "Downsample"; + LGraphTextureDownsample.desc = "Downsample Texture"; + LGraphTextureDownsample.widgets_info = { + iterations: { type:"number", step: 1, precision: 0, min: 1 }, + precision: { widget:"combo", values: LGraphTexture.MODE_VALUES } + }; + + LGraphTextureDownsample.prototype.onExecute = function() + { + var tex = this.getInputData(0); + if(!tex && !this._temp_texture) + return; + + if(!this.isOutputConnected(0)) + return; //saves work + + //we do not allow any texture different than texture 2D + if(!tex || tex.texture_type !== GL.TEXTURE_2D ) + return; + + var shader = LGraphTextureDownsample._shader; + if(!shader) + LGraphTextureDownsample._shader = shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureDownsample.pixel_shader ); + + var width = tex.width|0; + var height = tex.height|0; + var type = tex.type; + if(this.properties.precision === LGraphTexture.LOW) + type = gl.UNSIGNED_BYTE; + else if(this.properties.precision === LGraphTexture.HIGH) + type = gl.HIGH_PRECISION_FORMAT; + var iterations = this.properties.iterations || 1; + + var origin = tex; + var target = null; + + var temp = []; + var options = { + type: type, + format: tex.format + }; + + var offset = vec2.create(); + var uniforms = { + u_offset: offset + }; + + if( this._texture ) + GL.Texture.releaseTemporary( this._texture ); + + for(var i = 0; i < iterations; ++i) + { + offset[0] = 1/width; + offset[1] = 1/height; + width = width>>1 || 0; + height = height>>1 || 0; + target = GL.Texture.getTemporary( width, height, options ); + temp.push( target ); + origin.setParameter( GL.TEXTURE_MAG_FILTER, GL.NEAREST ); + origin.copyTo( target, shader, uniforms ); + if(width == 1 && height == 1) + break; //nothing else to do + origin = target; + } + + //keep the last texture used + this._texture = temp.pop(); + + //free the rest + for(var i = 0; i < temp.length; ++i) + GL.Texture.releaseTemporary( temp[i] ); + + if(this.properties.generate_mipmaps) + { + this._texture.bind(0); + gl.generateMipmap(this._texture.texture_type); + this._texture.unbind(0); + } + + this.setOutputData(0,this._texture); + } + + LGraphTextureDownsample.pixel_shader = "precision highp float;\n\ + precision highp float;\n\ + uniform sampler2D u_texture;\n\ + uniform vec2 u_offset;\n\ + varying vec2 v_coord;\n\ + \n\ + void main() {\n\ + vec4 color = texture2D(u_texture, v_coord );\n\ + color += texture2D(u_texture, v_coord + vec2( u_offset.x, 0.0 ) );\n\ + color += texture2D(u_texture, v_coord + vec2( 0.0, u_offset.y ) );\n\ + color += texture2D(u_texture, v_coord + vec2( u_offset.x, u_offset.y ) );\n\ + gl_FragColor = color * 0.25;\n\ + }\n\ + "; + + LiteGraph.registerNodeType("texture/downsample", LGraphTextureDownsample ); + + + + // Texture Copy ***************************************** + function LGraphTextureAverage() + { + this.addInput("Texture","Texture"); + this.addOutput("tex","Texture"); + this.addOutput("avg","vec4"); + this.addOutput("lum","number"); + this.properties = { mipmap_offset: 0, low_precision: false }; + + this._uniforms = { u_texture: 0, u_mipmap_offset: this.properties.mipmap_offset }; + this._luminance = new Float32Array(4); + } + + LGraphTextureAverage.title = "Average"; + LGraphTextureAverage.desc = "Compute a partial average (32 random samples) of a texture and stores it as a 1x1 pixel texture"; + + LGraphTextureAverage.prototype.onExecute = function() + { + var tex = this.getInputData(0); + if(!tex) + return; + + if(!this.isOutputConnected(0) && !this.isOutputConnected(1) && !this.isOutputConnected(2)) + return; //saves work + + if(!LGraphTextureAverage._shader) + { + LGraphTextureAverage._shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureAverage.pixel_shader); + //creates 32 random numbers and stores the, in two mat4 + var samples = new Float32Array(32); + for(var i = 0; i < 32; ++i) + samples[i] = Math.random(); + LGraphTextureAverage._shader.uniforms({u_samples_a: samples.subarray(0,16), u_samples_b: samples.subarray(16,32) }); + } + + var temp = this._temp_texture; + var type = gl.UNSIGNED_BYTE; + if(tex.type != type) //force floats, half floats cannot be read with gl.readPixels + type = gl.FLOAT; + + if(!temp || temp.type != type ) + this._temp_texture = new GL.Texture( 1, 1, { type: type, format: gl.RGBA, filter: gl.NEAREST }); + + var shader = LGraphTextureAverage._shader; + var uniforms = this._uniforms; + uniforms.u_mipmap_offset = this.properties.mipmap_offset; + this._temp_texture.drawTo(function(){ + tex.toViewport( shader, uniforms ); + }); + + this.setOutputData(0,this._temp_texture); + + if(this.isOutputConnected(1) || this.isOutputConnected(2)) + { + var pixel = this._temp_texture.getPixels(); + if(pixel) + { + var v = this._luminance; + var type = this._temp_texture.type; + v.set( pixel ); + if(type == gl.UNSIGNED_BYTE) + vec4.scale( v,v, 1/255 ); + else if(type == GL.HALF_FLOAT || type == GL.HALF_FLOAT_OES) + vec4.scale( v,v, 1/(255*255) ); //is this correct? + this.setOutputData(1,v); + this.setOutputData(2,(v[0] + v[1] + v[2]) / 3); + } + + } + } + + LGraphTextureAverage.pixel_shader = "precision highp float;\n\ + precision highp float;\n\ + uniform mat4 u_samples_a;\n\ + uniform mat4 u_samples_b;\n\ + uniform sampler2D u_texture;\n\ + uniform float u_mipmap_offset;\n\ + varying vec2 v_coord;\n\ + \n\ + void main() {\n\ + vec4 color = vec4(0.0);\n\ + for(int i = 0; i < 4; ++i)\n\ + for(int j = 0; j < 4; ++j)\n\ + {\n\ + color += texture2D(u_texture, vec2( u_samples_a[i][j], u_samples_b[i][j] ), u_mipmap_offset );\n\ + color += texture2D(u_texture, vec2( 1.0 - u_samples_a[i][j], 1.0 - u_samples_b[i][j] ), u_mipmap_offset );\n\ + }\n\ + gl_FragColor = color * 0.03125;\n\ + }\n\ + "; + + LiteGraph.registerNodeType("texture/average", LGraphTextureAverage ); + + // Image To Texture ***************************************** + function LGraphImageToTexture() + { + this.addInput("Image","image"); + this.addOutput("","Texture"); + this.properties = {}; + } + + LGraphImageToTexture.title = "Image to Texture"; + LGraphImageToTexture.desc = "Uploads an image to the GPU"; + //LGraphImageToTexture.widgets_info = { size: { widget:"combo", values:[0,32,64,128,256,512,1024,2048]} }; + + LGraphImageToTexture.prototype.onExecute = function() + { + var img = this.getInputData(0); + if(!img) + return; + + var width = img.videoWidth || img.width; + var height = img.videoHeight || img.height; + + //this is in case we are using a webgl canvas already, no need to reupload it + if(img.gltexture) + { + this.setOutputData(0,img.gltexture); + return; + } + + + var temp = this._temp_texture; + if(!temp || temp.width != width || temp.height != height ) + this._temp_texture = new GL.Texture( width, height, { format: gl.RGBA, filter: gl.LINEAR }); + + try + { + this._temp_texture.uploadImage(img); + } + catch(err) + { + console.error("image comes from an unsafe location, cannot be uploaded to webgl: " + err); + return; + } + + this.setOutputData(0,this._temp_texture); + } + + LiteGraph.registerNodeType("texture/imageToTexture", LGraphImageToTexture ); + + + // Texture LUT ***************************************** + function LGraphTextureLUT() + { + this.addInput("Texture","Texture"); + this.addInput("LUT","Texture"); + this.addInput("Intensity","number"); + this.addOutput("","Texture"); + this.properties = { intensity: 1, precision: LGraphTexture.DEFAULT, texture: null }; + + if(!LGraphTextureLUT._shader) + LGraphTextureLUT._shader = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureLUT.pixel_shader ); + } + + LGraphTextureLUT.widgets_info = { + "texture": { widget:"texture"}, + "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } + }; + + LGraphTextureLUT.title = "LUT"; + LGraphTextureLUT.desc = "Apply LUT to Texture"; + + LGraphTextureLUT.prototype.onExecute = function() + { + if(!this.isOutputConnected(0)) + return; //saves work + + var tex = this.getInputData(0); + + if(this.properties.precision === LGraphTexture.PASS_THROUGH ) + { + this.setOutputData(0,tex); + return; + } + + if(!tex) + return; + + var lut_tex = this.getInputData(1); + + if(!lut_tex) + lut_tex = LGraphTexture.getTexture( this.properties.texture ); + + if(!lut_tex) + { + this.setOutputData(0,tex); + return; + } + + lut_tex.bind(0); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR ); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); + gl.bindTexture(gl.TEXTURE_2D, null); + + var intensity = this.properties.intensity; + if( this.isInputConnected(2) ) + this.properties.intensity = intensity = this.getInputData(2); + + this._tex = LGraphTexture.getTargetTexture( tex, this._tex, this.properties.precision ); + + //var mesh = Mesh.getScreenQuad(); + + this._tex.drawTo(function() { + lut_tex.bind(1); + tex.toViewport( LGraphTextureLUT._shader, {u_texture:0, u_textureB:1, u_amount: intensity} ); + }); + + this.setOutputData(0,this._tex); + } + + LGraphTextureLUT.pixel_shader = "precision highp float;\n\ + precision highp float;\n\ + varying vec2 v_coord;\n\ + uniform sampler2D u_texture;\n\ + uniform sampler2D u_textureB;\n\ + uniform float u_amount;\n\ + \n\ + void main() {\n\ + lowp vec4 textureColor = clamp( texture2D(u_texture, v_coord), vec4(0.0), vec4(1.0) );\n\ + mediump float blueColor = textureColor.b * 63.0;\n\ + mediump vec2 quad1;\n\ + quad1.y = floor(floor(blueColor) / 8.0);\n\ + quad1.x = floor(blueColor) - (quad1.y * 8.0);\n\ + mediump vec2 quad2;\n\ + quad2.y = floor(ceil(blueColor) / 8.0);\n\ + quad2.x = ceil(blueColor) - (quad2.y * 8.0);\n\ + highp vec2 texPos1;\n\ + texPos1.x = (quad1.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);\n\ + texPos1.y = 1.0 - ((quad1.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g));\n\ + highp vec2 texPos2;\n\ + texPos2.x = (quad2.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);\n\ + texPos2.y = 1.0 - ((quad2.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g));\n\ + lowp vec4 newColor1 = texture2D(u_textureB, texPos1);\n\ + lowp vec4 newColor2 = texture2D(u_textureB, texPos2);\n\ + lowp vec4 newColor = mix(newColor1, newColor2, fract(blueColor));\n\ + gl_FragColor = vec4( mix( textureColor.rgb, newColor.rgb, u_amount), textureColor.w);\n\ + }\n\ + "; + + LiteGraph.registerNodeType("texture/LUT", LGraphTextureLUT ); + + // Texture Channels ***************************************** + function LGraphTextureChannels() + { + this.addInput("Texture","Texture"); + + this.addOutput("R","Texture"); + this.addOutput("G","Texture"); + this.addOutput("B","Texture"); + this.addOutput("A","Texture"); + + this.properties = {}; + if(!LGraphTextureChannels._shader) + LGraphTextureChannels._shader = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureChannels.pixel_shader ); + } + + LGraphTextureChannels.title = "Texture to Channels"; + LGraphTextureChannels.desc = "Split texture channels"; + + LGraphTextureChannels.prototype.onExecute = function() + { + var texA = this.getInputData(0); + if(!texA) return; + + if(!this._channels) + this._channels = Array(4); + + var connections = 0; + for(var i = 0; i < 4; i++) + { + if(this.isOutputConnected(i)) + { + if(!this._channels[i] || this._channels[i].width != texA.width || this._channels[i].height != texA.height || this._channels[i].type != texA.type) + this._channels[i] = new GL.Texture( texA.width, texA.height, { type: texA.type, format: gl.RGBA, filter: gl.LINEAR }); + connections++; + } + else + this._channels[i] = null; + } + + if(!connections) + return; + + gl.disable( gl.BLEND ); + gl.disable( gl.DEPTH_TEST ); + + var mesh = Mesh.getScreenQuad(); + var shader = LGraphTextureChannels._shader; + var masks = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]; + + for(var i = 0; i < 4; i++) + { + if(!this._channels[i]) + continue; + + this._channels[i].drawTo( function() { + texA.bind(0); + shader.uniforms({u_texture:0, u_mask: masks[i]}).draw(mesh); + }); + this.setOutputData(i, this._channels[i]); + } + } + + LGraphTextureChannels.pixel_shader = "precision highp float;\n\ + precision highp float;\n\ + varying vec2 v_coord;\n\ + uniform sampler2D u_texture;\n\ + uniform vec4 u_mask;\n\ + \n\ + void main() {\n\ + gl_FragColor = vec4( vec3( length( texture2D(u_texture, v_coord) * u_mask )), 1.0 );\n\ + }\n\ + "; + + LiteGraph.registerNodeType("texture/textureChannels", LGraphTextureChannels ); + + + // Texture Channels to Texture ***************************************** + function LGraphChannelsTexture() + { + this.addInput("R","Texture"); + this.addInput("G","Texture"); + this.addInput("B","Texture"); + this.addInput("A","Texture"); + + this.addOutput("Texture","Texture"); + + this.properties = {}; + if(!LGraphChannelsTexture._shader) + LGraphChannelsTexture._shader = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphChannelsTexture.pixel_shader ); + } + + LGraphChannelsTexture.title = "Channels to Texture"; + LGraphChannelsTexture.desc = "Split texture channels"; + + LGraphChannelsTexture.prototype.onExecute = function() + { + var tex = [ this.getInputData(0), + this.getInputData(1), + this.getInputData(2), + this.getInputData(3) ]; + + if(!tex[0] || !tex[1] || !tex[2] || !tex[3]) + return; + + gl.disable( gl.BLEND ); + gl.disable( gl.DEPTH_TEST ); + + var mesh = Mesh.getScreenQuad(); + var shader = LGraphChannelsTexture._shader; + + this._tex = LGraphTexture.getTargetTexture( tex[0], this._tex ); + + this._tex.drawTo( function() { + tex[0].bind(0); + tex[1].bind(1); + tex[2].bind(2); + tex[3].bind(3); + shader.uniforms({u_textureR:0, u_textureG:1, u_textureB:2, u_textureA:3 }).draw(mesh); + }); + this.setOutputData(0, this._tex); + } + + LGraphChannelsTexture.pixel_shader = "precision highp float;\n\ + precision highp float;\n\ + varying vec2 v_coord;\n\ + uniform sampler2D u_textureR;\n\ + uniform sampler2D u_textureG;\n\ + uniform sampler2D u_textureB;\n\ + uniform sampler2D u_textureA;\n\ + \n\ + void main() {\n\ + gl_FragColor = vec4( \ + texture2D(u_textureR, v_coord).r,\ + texture2D(u_textureG, v_coord).r,\ + texture2D(u_textureB, v_coord).r,\ + texture2D(u_textureA, v_coord).r);\n\ + }\n\ + "; + + LiteGraph.registerNodeType("texture/channelsTexture", LGraphChannelsTexture ); + + // Texture Color ***************************************** + function LGraphTextureColor() + { + this.addOutput("Texture","Texture"); + + this._tex_color = vec4.create(); + this.properties = { color: vec4.create(), precision: LGraphTexture.DEFAULT }; + } + + LGraphTextureColor.title = "Color"; + LGraphTextureColor.desc = "Generates a 1x1 texture with a constant color"; + + LGraphTextureColor.widgets_info = { + "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } + }; + + LGraphTextureColor.prototype.onDrawBackground = function( ctx ) + { + var c = this.properties.color; + ctx.fillStyle = "rgb(" + Math.floor(Math.clamp(c[0],0,1)*255) + "," + Math.floor(Math.clamp(c[1],0,1)*255) + "," + Math.floor(Math.clamp(c[2],0,1)*255) + ")"; + if(this.flags.collapsed) + this.boxcolor = ctx.fillStyle; + else + ctx.fillRect(0,0,this.size[0],this.size[1]); + } + + LGraphTextureColor.prototype.onExecute = function() + { + var type = this.properties.precision == LGraphTexture.HIGH ? LGraphTexture.HIGH_PRECISION_FORMAT : gl.UNSIGNED_BYTE; + + if(!this._tex || this._tex.type != type ) + this._tex = new GL.Texture(1,1,{ format: gl.RGBA, type: type, minFilter: gl.NEAREST }); + var color = this.properties.color; + + if(this.inputs) + for(var i = 0; i < this.inputs.length; i++) + { + var input = this.inputs[i]; + var v = this.getInputData(i); + if(v === undefined) + continue; + switch(input.name) + { + case 'RGB': + case 'RGBA': + color.set(v); + break; + case 'R': color[0] = v; break; + case 'G': color[1] = v; break; + case 'B': color[2] = v; break; + case 'A': color[3] = v; break; + } + } + + if( vec4.sqrDist( this._tex_color, color) > 0.001 ) + { + this._tex_color.set( color ); + this._tex.fill( color ); + } + this.setOutputData(0, this._tex); + } + + LGraphTextureColor.prototype.onGetInputs = function() + { + return [["RGB","vec3"],["RGBA","vec4"],["R","number"],["G","number"],["B","number"],["A","number"]]; + } + + LiteGraph.registerNodeType("texture/color", LGraphTextureColor ); + + // Texture Channels to Texture ***************************************** + function LGraphTextureGradient() + { + this.addInput("A","color"); + this.addInput("B","color"); + this.addOutput("Texture","Texture"); + + this.properties = { angle: 0, scale: 1, A:[0,0,0], B:[1,1,1], texture_size:32 }; + if(!LGraphTextureGradient._shader) + LGraphTextureGradient._shader = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureGradient.pixel_shader ); + + this._uniforms = { u_angle: 0, u_colorA: vec3.create(), u_colorB: vec3.create()}; + } + + LGraphTextureGradient.title = "Gradient"; + LGraphTextureGradient.desc = "Generates a gradient"; + LGraphTextureGradient["@A"] = { type:"color" }; + LGraphTextureGradient["@B"] = { type:"color" }; + LGraphTextureGradient["@texture_size"] = { type:"enum", values:[32,64,128,256,512] }; + + LGraphTextureGradient.prototype.onExecute = function() + { + gl.disable( gl.BLEND ); + gl.disable( gl.DEPTH_TEST ); + + var mesh = GL.Mesh.getScreenQuad(); + var shader = LGraphTextureGradient._shader; + + var A = this.getInputData(0); + if(!A) + A = this.properties.A; + var B = this.getInputData(1); + if(!B) + B = this.properties.B; + + //angle and scale + for(var i = 2; i < this.inputs.length; i++) + { + var input = this.inputs[i]; + var v = this.getInputData(i); + if(v === undefined) + continue; + this.properties[ input.name ] = v; + } + + var uniforms = this._uniforms; + this._uniforms.u_angle = this.properties.angle * DEG2RAD; + this._uniforms.u_scale = this.properties.scale; + vec3.copy( uniforms.u_colorA, A ); + vec3.copy( uniforms.u_colorB, B ); + + var size = parseInt( this.properties.texture_size ); + if(!this._tex || this._tex.width != size ) + this._tex = new GL.Texture( size, size, { format: gl.RGB, filter: gl.LINEAR }); + + this._tex.drawTo( function() { + shader.uniforms(uniforms).draw(mesh); + }); + this.setOutputData(0, this._tex); + } + + LGraphTextureGradient.prototype.onGetInputs = function() + { + return [["angle","number"],["scale","number"]]; + } + + LGraphTextureGradient.pixel_shader = "precision highp float;\n\ + precision highp float;\n\ + varying vec2 v_coord;\n\ + uniform float u_angle;\n\ + uniform float u_scale;\n\ + uniform vec3 u_colorA;\n\ + uniform vec3 u_colorB;\n\ + \n\ + vec2 rotate(vec2 v, float angle)\n\ + {\n\ + vec2 result;\n\ + float _cos = cos(angle);\n\ + float _sin = sin(angle);\n\ + result.x = v.x * _cos - v.y * _sin;\n\ + result.y = v.x * _sin + v.y * _cos;\n\ + return result;\n\ + }\n\ + void main() {\n\ + float f = (rotate(u_scale * (v_coord - vec2(0.5)), u_angle) + vec2(0.5)).x;\n\ + vec3 color = mix(u_colorA,u_colorB,clamp(f,0.0,1.0));\n\ + gl_FragColor = vec4(color,1.0);\n\ + }\n\ + "; + + LiteGraph.registerNodeType("texture/gradient", LGraphTextureGradient ); + + // Texture Mix ***************************************** + function LGraphTextureMix() + { + this.addInput("A","Texture"); + this.addInput("B","Texture"); + this.addInput("Mixer","Texture"); + + this.addOutput("Texture","Texture"); + this.properties = { factor: 0.5, precision: LGraphTexture.DEFAULT }; + this._uniforms = { u_textureA:0, u_textureB:1, u_textureMix:2, u_mix: vec4.create() }; + } + + LGraphTextureMix.title = "Mix"; + LGraphTextureMix.desc = "Generates a texture mixing two textures"; + + LGraphTextureMix.widgets_info = { + "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } + }; + + LGraphTextureMix.prototype.onExecute = function() + { + var texA = this.getInputData(0); + + if(!this.isOutputConnected(0)) + return; //saves work + + if(this.properties.precision === LGraphTexture.PASS_THROUGH ) + { + this.setOutputData(0,texA); + return; + } + + var texB = this.getInputData(1); + if(!texA || !texB ) + return; + + var texMix = this.getInputData(2); + + var factor = this.getInputData(3); + + + this._tex = LGraphTexture.getTargetTexture( texA, this._tex, this.properties.precision ); + + gl.disable( gl.BLEND ); + gl.disable( gl.DEPTH_TEST ); + + var mesh = Mesh.getScreenQuad(); + var shader = null; + var uniforms = this._uniforms; + if(texMix) + { + shader = LGraphTextureMix._shader_tex; + if(!shader) + shader = LGraphTextureMix._shader_tex = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureMix.pixel_shader, {"MIX_TEX":""}); + } + else + { + shader = LGraphTextureMix._shader_factor; + if(!shader) + shader = LGraphTextureMix._shader_factor = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureMix.pixel_shader ); + var f = factor == null ? this.properties.factor : factor; + uniforms.u_mix.set([f,f,f,f]); + } + + this._tex.drawTo( function() { + texA.bind(0); + texB.bind(1); + if(texMix) + texMix.bind(2); + shader.uniforms( uniforms ).draw(mesh); + }); + + this.setOutputData(0, this._tex); + } + + LGraphTextureMix.prototype.onGetInputs = function() + { + return [["factor","number"]]; + } + + LGraphTextureMix.pixel_shader = "precision highp float;\n\ + precision highp float;\n\ + varying vec2 v_coord;\n\ + uniform sampler2D u_textureA;\n\ + uniform sampler2D u_textureB;\n\ + #ifdef MIX_TEX\n\ + uniform sampler2D u_textureMix;\n\ + #else\n\ + uniform vec4 u_mix;\n\ + #endif\n\ + \n\ + void main() {\n\ + #ifdef MIX_TEX\n\ + vec4 f = texture2D(u_textureMix, v_coord);\n\ + #else\n\ + vec4 f = u_mix;\n\ + #endif\n\ + gl_FragColor = mix( texture2D(u_textureA, v_coord), texture2D(u_textureB, v_coord), f );\n\ + }\n\ + "; + + LiteGraph.registerNodeType("texture/mix", LGraphTextureMix ); + + // Texture Edges detection ***************************************** + function LGraphTextureEdges() + { + this.addInput("Tex.","Texture"); + + this.addOutput("Edges","Texture"); + this.properties = { invert: true, threshold: false, factor: 1, precision: LGraphTexture.DEFAULT }; + + if(!LGraphTextureEdges._shader) + LGraphTextureEdges._shader = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureEdges.pixel_shader ); + } + + LGraphTextureEdges.title = "Edges"; + LGraphTextureEdges.desc = "Detects edges"; + + LGraphTextureEdges.widgets_info = { + "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } + }; + + LGraphTextureEdges.prototype.onExecute = function() + { + if(!this.isOutputConnected(0)) + return; //saves work + + var tex = this.getInputData(0); + + if(this.properties.precision === LGraphTexture.PASS_THROUGH ) + { + this.setOutputData(0,tex); + return; + } + + if(!tex) return; + + this._tex = LGraphTexture.getTargetTexture( tex, this._tex, this.properties.precision ); + + gl.disable( gl.BLEND ); + gl.disable( gl.DEPTH_TEST ); + + var mesh = Mesh.getScreenQuad(); + var shader = LGraphTextureEdges._shader; + var invert = this.properties.invert; + var factor = this.properties.factor; + var threshold = this.properties.threshold ? 1 : 0; + + this._tex.drawTo( function() { + tex.bind(0); + shader.uniforms({u_texture:0, u_isize:[1/tex.width,1/tex.height], u_factor: factor, u_threshold: threshold, u_invert: invert ? 1 : 0}).draw(mesh); + }); + + this.setOutputData(0, this._tex); + } + + LGraphTextureEdges.pixel_shader = "precision highp float;\n\ + precision highp float;\n\ + varying vec2 v_coord;\n\ + uniform sampler2D u_texture;\n\ + uniform vec2 u_isize;\n\ + uniform int u_invert;\n\ + uniform float u_factor;\n\ + uniform float u_threshold;\n\ + \n\ + void main() {\n\ + vec4 center = texture2D(u_texture, v_coord);\n\ + vec4 up = texture2D(u_texture, v_coord + u_isize * vec2(0.0,1.0) );\n\ + vec4 down = texture2D(u_texture, v_coord + u_isize * vec2(0.0,-1.0) );\n\ + vec4 left = texture2D(u_texture, v_coord + u_isize * vec2(1.0,0.0) );\n\ + vec4 right = texture2D(u_texture, v_coord + u_isize * vec2(-1.0,0.0) );\n\ + vec4 diff = abs(center - up) + abs(center - down) + abs(center - left) + abs(center - right);\n\ + diff *= u_factor;\n\ + if(u_invert == 1)\n\ + diff.xyz = vec3(1.0) - diff.xyz;\n\ + if( u_threshold == 0.0 )\n\ + gl_FragColor = vec4( diff.xyz, center.a );\n\ + else\n\ + gl_FragColor = vec4( diff.x > 0.5 ? 1.0 : 0.0, diff.y > 0.5 ? 1.0 : 0.0, diff.z > 0.5 ? 1.0 : 0.0, center.a );\n\ + }\n\ + "; + + LiteGraph.registerNodeType("texture/edges", LGraphTextureEdges ); + + // Texture Depth ***************************************** + function LGraphTextureDepthRange() + { + this.addInput("Texture","Texture"); + this.addInput("Distance","number"); + this.addInput("Range","number"); + this.addOutput("Texture","Texture"); + this.properties = { distance:100, range: 50, only_depth: false, high_precision: false }; + this._uniforms = {u_texture:0, u_distance: 100, u_range: 50, u_camera_planes: null }; + } + + LGraphTextureDepthRange.title = "Depth Range"; + LGraphTextureDepthRange.desc = "Generates a texture with a depth range"; + + LGraphTextureDepthRange.prototype.onExecute = function() + { + if(!this.isOutputConnected(0)) + return; //saves work + + var tex = this.getInputData(0); + if(!tex) return; + + var precision = gl.UNSIGNED_BYTE; + if(this.properties.high_precision) + precision = gl.half_float_ext ? gl.HALF_FLOAT_OES : gl.FLOAT; + + if(!this._temp_texture || this._temp_texture.type != precision || + this._temp_texture.width != tex.width || this._temp_texture.height != tex.height) + this._temp_texture = new GL.Texture( tex.width, tex.height, { type: precision, format: gl.RGBA, filter: gl.LINEAR }); + + var uniforms = this._uniforms; + + //iterations + var distance = this.properties.distance; + if( this.isInputConnected(1) ) + { + distance = this.getInputData(1); + this.properties.distance = distance; + } + + var range = this.properties.range; + if( this.isInputConnected(2) ) + { + range = this.getInputData(2); + this.properties.range = range; + } + + uniforms.u_distance = distance; + uniforms.u_range = range; + + gl.disable( gl.BLEND ); + gl.disable( gl.DEPTH_TEST ); + var mesh = Mesh.getScreenQuad(); + if(!LGraphTextureDepthRange._shader) + { + LGraphTextureDepthRange._shader = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureDepthRange.pixel_shader ); + LGraphTextureDepthRange._shader_onlydepth = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureDepthRange.pixel_shader, { ONLY_DEPTH:""} ); + } + var shader = this.properties.only_depth ? LGraphTextureDepthRange._shader_onlydepth : LGraphTextureDepthRange._shader; + + //NEAR AND FAR PLANES + var planes = null; + if( tex.near_far_planes ) + planes = tex.near_far_planes; + else if( window.LS && LS.Renderer._main_camera ) + planes = LS.Renderer._main_camera._uniforms.u_camera_planes; + else + planes = [0.1,1000]; //hardcoded + uniforms.u_camera_planes = planes; + + + this._temp_texture.drawTo( function() { + tex.bind(0); + shader.uniforms( uniforms ).draw(mesh); + }); + + this._temp_texture.near_far_planes = planes; + this.setOutputData(0, this._temp_texture ); + } + + LGraphTextureDepthRange.pixel_shader = "precision highp float;\n\ + precision highp float;\n\ + varying vec2 v_coord;\n\ + uniform sampler2D u_texture;\n\ + uniform vec2 u_camera_planes;\n\ + uniform float u_distance;\n\ + uniform float u_range;\n\ + \n\ + float LinearDepth()\n\ + {\n\ + float zNear = u_camera_planes.x;\n\ + float zFar = u_camera_planes.y;\n\ + float depth = texture2D(u_texture, v_coord).x;\n\ + depth = depth * 2.0 - 1.0;\n\ + return zNear * (depth + 1.0) / (zFar + zNear - depth * (zFar - zNear));\n\ + }\n\ + \n\ + void main() {\n\ + float depth = LinearDepth();\n\ + #ifdef ONLY_DEPTH\n\ + gl_FragColor = vec4(depth);\n\ + #else\n\ + float diff = abs(depth * u_camera_planes.y - u_distance);\n\ + float dof = 1.0;\n\ + if(diff <= u_range)\n\ + dof = diff / u_range;\n\ + gl_FragColor = vec4(dof);\n\ + #endif\n\ + }\n\ + "; + + LiteGraph.registerNodeType("texture/depth_range", LGraphTextureDepthRange ); + + // Texture Blur ***************************************** + function LGraphTextureBlur() + { + this.addInput("Texture","Texture"); + this.addInput("Iterations","number"); + this.addInput("Intensity","number"); + this.addOutput("Blurred","Texture"); + this.properties = { intensity: 1, iterations: 1, preserve_aspect: false, scale:[1,1], precision: LGraphTexture.DEFAULT }; + } + + LGraphTextureBlur.title = "Blur"; + LGraphTextureBlur.desc = "Blur a texture"; + + LGraphTextureBlur.widgets_info = { + precision: { widget:"combo", values: LGraphTexture.MODE_VALUES } + }; + + LGraphTextureBlur.max_iterations = 20; + + LGraphTextureBlur.prototype.onExecute = function() + { + var tex = this.getInputData(0); + if(!tex) + return; + + if(!this.isOutputConnected(0)) + return; //saves work + + var temp = this._final_texture; + + if(!temp || temp.width != tex.width || temp.height != tex.height || temp.type != tex.type ) + { + //we need two textures to do the blurring + //this._temp_texture = new GL.Texture( tex.width, tex.height, { type: tex.type, format: gl.RGBA, filter: gl.LINEAR }); + temp = this._final_texture = new GL.Texture( tex.width, tex.height, { type: tex.type, format: gl.RGBA, filter: gl.LINEAR }); + } + + //iterations + var iterations = this.properties.iterations; + if( this.isInputConnected(1) ) + { + iterations = this.getInputData(1); + this.properties.iterations = iterations; + } + iterations = Math.min( Math.floor(iterations), LGraphTextureBlur.max_iterations ); + if(iterations == 0) //skip blurring + { + this.setOutputData(0, tex); + return; + } + + var intensity = this.properties.intensity; + if( this.isInputConnected(2) ) + { + intensity = this.getInputData(2); + this.properties.intensity = intensity; + } + + //blur sometimes needs an aspect correction + var aspect = LiteGraph.camera_aspect; + if(!aspect && window.gl !== undefined) + aspect = gl.canvas.height / gl.canvas.width; + if(!aspect) + aspect = 1; + aspect = this.properties.preserve_aspect ? aspect : 1; + + var scale = this.properties.scale || [1,1]; + tex.applyBlur( aspect * scale[0], scale[1], intensity, temp ); + for(var i = 1; i < iterations; ++i) + temp.applyBlur( aspect * scale[0] * (i+1), scale[1] * (i+1), intensity ); + + this.setOutputData(0, temp ); + } + + /* + LGraphTextureBlur.pixel_shader = "precision highp float;\n\ + precision highp float;\n\ + varying vec2 v_coord;\n\ + uniform sampler2D u_texture;\n\ + uniform vec2 u_offset;\n\ + uniform float u_intensity;\n\ + void main() {\n\ + vec4 sum = vec4(0.0);\n\ + vec4 center = texture2D(u_texture, v_coord);\n\ + sum += texture2D(u_texture, v_coord + u_offset * -4.0) * 0.05/0.98;\n\ + sum += texture2D(u_texture, v_coord + u_offset * -3.0) * 0.09/0.98;\n\ + sum += texture2D(u_texture, v_coord + u_offset * -2.0) * 0.12/0.98;\n\ + sum += texture2D(u_texture, v_coord + u_offset * -1.0) * 0.15/0.98;\n\ + sum += center * 0.16/0.98;\n\ + sum += texture2D(u_texture, v_coord + u_offset * 4.0) * 0.05/0.98;\n\ + sum += texture2D(u_texture, v_coord + u_offset * 3.0) * 0.09/0.98;\n\ + sum += texture2D(u_texture, v_coord + u_offset * 2.0) * 0.12/0.98;\n\ + sum += texture2D(u_texture, v_coord + u_offset * 1.0) * 0.15/0.98;\n\ + gl_FragColor = u_intensity * sum;\n\ + }\n\ + "; + */ + + LiteGraph.registerNodeType("texture/blur", LGraphTextureBlur ); + + + // Texture Glow ***************************************** + //based in https://catlikecoding.com/unity/tutorials/advanced-rendering/bloom/ + function LGraphTextureGlow() + { + this.addInput("in","Texture"); + this.addInput("dirt","Texture"); + this.addOutput("out","Texture"); + this.addOutput("glow","Texture"); + this.properties = { enabled: true, intensity: 1, persistence: 0.99, iterations:16, threshold:0, scale: 1, dirt_factor: 0.5, precision: LGraphTexture.DEFAULT }; + this._textures = []; + this._uniforms = { u_intensity: 1, u_texture: 0, u_glow_texture: 1, u_threshold: 0, u_texel_size: vec2.create() }; + } + + LGraphTextureGlow.title = "Glow"; + LGraphTextureGlow.desc = "Filters a texture giving it a glow effect"; + LGraphTextureGlow.weights = new Float32Array( [0.5,0.4,0.3,0.2] ); + + LGraphTextureGlow.widgets_info = { + "iterations": { type:"number", min: 0, max: 16, step: 1, precision: 0 }, + "threshold": { type:"number", min: 0, max: 10, step: 0.01, precision: 2 }, + "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } + }; + + LGraphTextureGlow.prototype.onGetInputs = function(){ + return [["enabled","boolean"],["threshold","number"],["intensity","number"],["persistence","number"],["iterations","number"],["dirt_factor","number"]]; + } + + LGraphTextureGlow.prototype.onGetOutputs = function(){ + return [["average","Texture"]]; + } + + LGraphTextureGlow.prototype.onExecute = function() + { + var tex = this.getInputData(0); + if(!tex) + return; + + if(!this.isAnyOutputConnected()) + return; //saves work + + if(this.properties.precision === LGraphTexture.PASS_THROUGH || this.getInputOrProperty("enabled" ) === false ) + { + this.setOutputData(0,tex); + return; + } + + var width = tex.width; + var height = tex.height; + + var texture_info = { format: tex.format, type: tex.type, minFilter: GL.LINEAR, magFilter: GL.LINEAR, wrap: gl.CLAMP_TO_EDGE }; + var type = LGraphTexture.getTextureType( this.properties.precision, tex ); + + var uniforms = this._uniforms; + var textures = this._textures; + + //cut + var shader = LGraphTextureGlow._cut_shader; + if(!shader) + shader = LGraphTextureGlow._cut_shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureGlow.cut_pixel_shader ); + + gl.disable( gl.DEPTH_TEST ); + gl.disable( gl.BLEND ); + + uniforms.u_threshold = this.getInputOrProperty("threshold"); + var currentDestination = textures[0] = GL.Texture.getTemporary( width, height, texture_info ); + tex.blit( currentDestination, shader.uniforms(uniforms) ); + var currentSource = currentDestination; + + var iterations = this.getInputOrProperty("iterations"); + iterations = Math.clamp( iterations, 1, 16) | 0; + var texel_size = uniforms.u_texel_size; + var intensity = this.getInputOrProperty("intensity"); + + uniforms.u_intensity = 1; + uniforms.u_delta = this.properties.scale; //1 + + //downscale/upscale shader + var shader = LGraphTextureGlow._shader; + if(!shader) + shader = LGraphTextureGlow._shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureGlow.scale_pixel_shader ); + + var i = 1; + //downscale + for (;i < iterations; i++) { + width = width>>1; + if( (height|0) > 1 ) + height = height>>1; + if( width < 2 ) + break; + currentDestination = textures[i] = GL.Texture.getTemporary( width, height, texture_info ); + texel_size[0] = 1 / currentSource.width; texel_size[1] = 1 / currentSource.height; + currentSource.blit( currentDestination, shader.uniforms(uniforms) ); + currentSource = currentDestination; + } + + //average + if(this.isOutputConnected(2)) + { + var average_texture = this._average_texture; + if(!average_texture || average_texture.type != tex.type || average_texture.format != tex.format ) + average_texture = this._average_texture = new GL.Texture( 1, 1, { type: tex.type, format: tex.format, filter: gl.LINEAR }); + texel_size[0] = 1 / currentSource.width; texel_size[1] = 1 / currentSource.height; + uniforms.u_intensity = intensity; + uniforms.u_delta = 1; + currentSource.blit( average_texture, shader.uniforms(uniforms) ); + this.setOutputData( 2, average_texture ); + } + + //upscale and blend + gl.enable( gl.BLEND ); + gl.blendFunc( gl.ONE, gl.ONE ); + uniforms.u_intensity = this.getInputOrProperty("persistence"); + uniforms.u_delta = 0.5; + + for (i -= 2; i >= 0; i--) // i-=2 => -1 to point to last element in array, -1 to go to texture above + { + currentDestination = textures[i]; + textures[i] = null; + texel_size[0] = 1 / currentSource.width; texel_size[1] = 1 / currentSource.height; + currentSource.blit( currentDestination, shader.uniforms(uniforms) ); + GL.Texture.releaseTemporary( currentSource ); + currentSource = currentDestination; + } + gl.disable( gl.BLEND ); + + //glow + if(this.isOutputConnected(1)) + { + var glow_texture = this._glow_texture; + if(!glow_texture || glow_texture.width != tex.width || glow_texture.height != tex.height || glow_texture.type != type || glow_texture.format != tex.format ) + glow_texture = this._glow_texture = new GL.Texture( tex.width, tex.height, { type: type, format: tex.format, filter: gl.LINEAR }); + currentSource.blit( glow_texture ); + this.setOutputData( 1, glow_texture); + } + + //final composition + if(this.isOutputConnected(0)) + { + var final_texture = this._final_texture; + if(!final_texture || final_texture.width != tex.width || final_texture.height != tex.height || final_texture.type != type || final_texture.format != tex.format ) + final_texture = this._final_texture = new GL.Texture( tex.width, tex.height, { type: type, format: tex.format, filter: gl.LINEAR }); + + var dirt_texture = this.getInputData(1); + var dirt_factor = this.getInputOrProperty("dirt_factor"); + + uniforms.u_intensity = intensity; + + shader = dirt_texture ? LGraphTextureGlow._dirt_final_shader : LGraphTextureGlow._final_shader; + if(!shader) + { + if(dirt_texture) + shader = LGraphTextureGlow._dirt_final_shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureGlow.final_pixel_shader, { USE_DIRT: "" } ); + else + shader = LGraphTextureGlow._final_shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureGlow.final_pixel_shader ); + } + + final_texture.drawTo( function(){ + tex.bind(0); + currentSource.bind(1); + if(dirt_texture) + { + shader.setUniform( "u_dirt_factor", dirt_factor ); + shader.setUniform( "u_dirt_texture", dirt_texture.bind(2) ); + } + shader.toViewport( uniforms ); + }); + this.setOutputData( 0, final_texture ); + } + + GL.Texture.releaseTemporary( currentSource ); + } + + LGraphTextureGlow.cut_pixel_shader = "precision highp float;\n\ + varying vec2 v_coord;\n\ + uniform sampler2D u_texture;\n\ + uniform float u_threshold;\n\ + void main() {\n\ + gl_FragColor = max( texture2D( u_texture, v_coord ) - vec4( u_threshold ), vec4(0.0) );\n\ + }" + + LGraphTextureGlow.scale_pixel_shader = "precision highp float;\n\ + varying vec2 v_coord;\n\ + uniform sampler2D u_texture;\n\ + uniform vec2 u_texel_size;\n\ + uniform float u_delta;\n\ + uniform float u_intensity;\n\ + \n\ + vec4 sampleBox(vec2 uv) {\n\ + vec4 o = u_texel_size.xyxy * vec2(-u_delta, u_delta).xxyy;\n\ + vec4 s = texture2D( u_texture, uv + o.xy ) + texture2D( u_texture, uv + o.zy) + texture2D( u_texture, uv + o.xw) + texture2D( u_texture, uv + o.zw);\n\ + return s * 0.25;\n\ + }\n\ + void main() {\n\ + gl_FragColor = u_intensity * sampleBox( v_coord );\n\ + }" + + LGraphTextureGlow.final_pixel_shader = "precision highp float;\n\ + varying vec2 v_coord;\n\ + uniform sampler2D u_texture;\n\ + uniform sampler2D u_glow_texture;\n\ + #ifdef USE_DIRT\n\ + uniform sampler2D u_dirt_texture;\n\ + #endif\n\ + uniform vec2 u_texel_size;\n\ + uniform float u_delta;\n\ + uniform float u_intensity;\n\ + uniform float u_dirt_factor;\n\ + \n\ + vec4 sampleBox(vec2 uv) {\n\ + vec4 o = u_texel_size.xyxy * vec2(-u_delta, u_delta).xxyy;\n\ + vec4 s = texture2D( u_glow_texture, uv + o.xy ) + texture2D( u_glow_texture, uv + o.zy) + texture2D( u_glow_texture, uv + o.xw) + texture2D( u_glow_texture, uv + o.zw);\n\ + return s * 0.25;\n\ + }\n\ + void main() {\n\ + vec4 glow = sampleBox( v_coord );\n\ + #ifdef USE_DIRT\n\ + glow = mix( glow, glow * texture2D( u_dirt_texture, v_coord ), u_dirt_factor );\n\ + #endif\n\ + gl_FragColor = texture2D( u_texture, v_coord ) + u_intensity * glow;\n\ + }" + + LiteGraph.registerNodeType("texture/glow", LGraphTextureGlow ); + + + // Texture Blur ***************************************** + function LGraphTextureKuwaharaFilter() + { + this.addInput("Texture","Texture"); + this.addOutput("Filtered","Texture"); + this.properties = { intensity: 1, radius: 5 }; + } + + LGraphTextureKuwaharaFilter.title = "Kuwahara Filter"; + LGraphTextureKuwaharaFilter.desc = "Filters a texture giving an artistic oil canvas painting"; + + LGraphTextureKuwaharaFilter.max_radius = 10; + LGraphTextureKuwaharaFilter._shaders = []; + + LGraphTextureKuwaharaFilter.prototype.onExecute = function() + { + var tex = this.getInputData(0); + if(!tex) + return; + + if(!this.isOutputConnected(0)) + return; //saves work + + var temp = this._temp_texture; + + if(!temp || temp.width != tex.width || temp.height != tex.height || temp.type != tex.type ) + { + //we need two textures to do the blurring + this._temp_texture = new GL.Texture( tex.width, tex.height, { type: tex.type, format: gl.RGBA, filter: gl.LINEAR }); + //this._final_texture = new GL.Texture( tex.width, tex.height, { type: tex.type, format: gl.RGBA, filter: gl.LINEAR }); + } + + //iterations + var radius = this.properties.radius; + radius = Math.min( Math.floor(radius), LGraphTextureKuwaharaFilter.max_radius ); + if(radius == 0) //skip blurring + { + this.setOutputData(0, tex); + return; + } + + var intensity = this.properties.intensity; + + //blur sometimes needs an aspect correction + var aspect = LiteGraph.camera_aspect; + if(!aspect && window.gl !== undefined) + aspect = gl.canvas.height / gl.canvas.width; + if(!aspect) + aspect = 1; + aspect = this.properties.preserve_aspect ? aspect : 1; + + if(!LGraphTextureKuwaharaFilter._shaders[ radius ]) + LGraphTextureKuwaharaFilter._shaders[ radius ] = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureKuwaharaFilter.pixel_shader, { RADIUS: radius.toFixed(0) }); + + var shader = LGraphTextureKuwaharaFilter._shaders[ radius ]; + var mesh = GL.Mesh.getScreenQuad(); + tex.bind(0); + + this._temp_texture.drawTo( function() { + shader.uniforms({ u_texture: 0, u_intensity: intensity, u_resolution: [tex.width, tex.height], u_iResolution: [1/tex.width,1/tex.height]}).draw(mesh); + }); + + this.setOutputData(0, this._temp_texture); + } + +//from https://www.shadertoy.com/view/MsXSz4 +LGraphTextureKuwaharaFilter.pixel_shader = "\n\ + precision highp float;\n\ + varying vec2 v_coord;\n\ + uniform sampler2D u_texture;\n\ + uniform float u_intensity;\n\ + uniform vec2 u_resolution;\n\ + uniform vec2 u_iResolution;\n\ + #ifndef RADIUS\n\ + #define RADIUS 7\n\ + #endif\n\ + void main() {\n\ + \n\ + const int radius = RADIUS;\n\ + vec2 fragCoord = v_coord;\n\ + vec2 src_size = u_iResolution;\n\ + vec2 uv = v_coord;\n\ + float n = float((radius + 1) * (radius + 1));\n\ + int i;\n\ + int j;\n\ + vec3 m0 = vec3(0.0); vec3 m1 = vec3(0.0); vec3 m2 = vec3(0.0); vec3 m3 = vec3(0.0);\n\ + vec3 s0 = vec3(0.0); vec3 s1 = vec3(0.0); vec3 s2 = vec3(0.0); vec3 s3 = vec3(0.0);\n\ + vec3 c;\n\ + \n\ + for (int j = -radius; j <= 0; ++j) {\n\ + for (int i = -radius; i <= 0; ++i) {\n\ + c = texture2D(u_texture, uv + vec2(i,j) * src_size).rgb;\n\ + m0 += c;\n\ + s0 += c * c;\n\ + }\n\ + }\n\ + \n\ + for (int j = -radius; j <= 0; ++j) {\n\ + for (int i = 0; i <= radius; ++i) {\n\ + c = texture2D(u_texture, uv + vec2(i,j) * src_size).rgb;\n\ + m1 += c;\n\ + s1 += c * c;\n\ + }\n\ + }\n\ + \n\ + for (int j = 0; j <= radius; ++j) {\n\ + for (int i = 0; i <= radius; ++i) {\n\ + c = texture2D(u_texture, uv + vec2(i,j) * src_size).rgb;\n\ + m2 += c;\n\ + s2 += c * c;\n\ + }\n\ + }\n\ + \n\ + for (int j = 0; j <= radius; ++j) {\n\ + for (int i = -radius; i <= 0; ++i) {\n\ + c = texture2D(u_texture, uv + vec2(i,j) * src_size).rgb;\n\ + m3 += c;\n\ + s3 += c * c;\n\ + }\n\ + }\n\ + \n\ + float min_sigma2 = 1e+2;\n\ + m0 /= n;\n\ + s0 = abs(s0 / n - m0 * m0);\n\ + \n\ + float sigma2 = s0.r + s0.g + s0.b;\n\ + if (sigma2 < min_sigma2) {\n\ + min_sigma2 = sigma2;\n\ + gl_FragColor = vec4(m0, 1.0);\n\ + }\n\ + \n\ + m1 /= n;\n\ + s1 = abs(s1 / n - m1 * m1);\n\ + \n\ + sigma2 = s1.r + s1.g + s1.b;\n\ + if (sigma2 < min_sigma2) {\n\ + min_sigma2 = sigma2;\n\ + gl_FragColor = vec4(m1, 1.0);\n\ + }\n\ + \n\ + m2 /= n;\n\ + s2 = abs(s2 / n - m2 * m2);\n\ + \n\ + sigma2 = s2.r + s2.g + s2.b;\n\ + if (sigma2 < min_sigma2) {\n\ + min_sigma2 = sigma2;\n\ + gl_FragColor = vec4(m2, 1.0);\n\ + }\n\ + \n\ + m3 /= n;\n\ + s3 = abs(s3 / n - m3 * m3);\n\ + \n\ + sigma2 = s3.r + s3.g + s3.b;\n\ + if (sigma2 < min_sigma2) {\n\ + min_sigma2 = sigma2;\n\ + gl_FragColor = vec4(m3, 1.0);\n\ + }\n\ + }\n\ + "; + + LiteGraph.registerNodeType("texture/kuwahara", LGraphTextureKuwaharaFilter ); + + + // Texture Webcam ***************************************** + function LGraphTextureWebcam() + { + this.addOutput("Webcam","Texture"); + this.properties = { texture_name: "", facingMode: "user" }; + this.boxcolor = "black"; + this.version = 0; + } + + LGraphTextureWebcam.title = "Webcam"; + LGraphTextureWebcam.desc = "Webcam texture"; + + + LGraphTextureWebcam.prototype.openStream = function() + { + if (!navigator.getUserMedia) { + //console.log('getUserMedia() is not supported in your browser, use chrome and enable WebRTC from about://flags'); + return; + } + + this._waiting_confirmation = true; + + // Not showing vendor prefixes. + var constraints = { audio: false, video: { facingMode: this.properties.facingMode } }; + navigator.mediaDevices.getUserMedia( constraints ).then( this.streamReady.bind(this) ).catch( onFailSoHard ); + + var that = this; + function onFailSoHard(e) { + console.log('Webcam rejected', e); + that._webcam_stream = false; + that.boxcolor = "red"; + that.trigger("stream_error"); + }; + } + + LGraphTextureWebcam.prototype.closeStream = function() + { + if(this._webcam_stream) + { + var tracks = this._webcam_stream.getTracks(); + if(tracks.length) + { + for(var i = 0;i < tracks.length; ++i) + tracks[i].stop(); + } + this._webcam_stream = null; + this._video = null; + this.boxcolor = "black"; + this.trigger("stream_closed"); + } + } + + LGraphTextureWebcam.prototype.streamReady = function(localMediaStream) + { + this._webcam_stream = localMediaStream; + //this._waiting_confirmation = false; + this.boxcolor = "green"; + var video = this._video; + if(!video) + { + video = document.createElement("video"); + video.autoplay = true; + video.srcObject = localMediaStream; + this._video = video; + //document.body.appendChild( video ); //debug + //when video info is loaded (size and so) + video.onloadedmetadata = function(e) { + // Ready to go. Do some stuff. + console.log(e); + }; + } + this.trigger("stream_ready",video); + } + + LGraphTextureWebcam.prototype.onPropertyChanged = function(name,value) + { + if(name == "facingMode") + { + this.properties.facingMode = value; + this.closeStream(); + this.openStream(); + } + } + + LGraphTextureWebcam.prototype.onRemoved = function() + { + if(!this._webcam_stream) + return; + var tracks = this._webcam_stream.getTracks(); if(tracks.length) { for(var i = 0;i < tracks.length; ++i) tracks[i].stop(); } + this._webcam_stream = null; this._video = null; - this.boxcolor = "black"; - this.trigger("stream_closed"); } -} -ImageWebcam.prototype.onPropertyChanged = function(name,value) -{ - if(name == "facingMode") + LGraphTextureWebcam.prototype.onDrawBackground = function(ctx) { - this.properties.facingMode = value; - this.closeStream(); - this.openStream(); + if(this.flags.collapsed || this.size[1] <= 20) + return; + + if(!this._video) + return; + + //render to graph canvas + ctx.save(); + if(!ctx.webgl) //reverse image + ctx.drawImage(this._video, 0, 0, this.size[0], this.size[1]); + else + { + if(this._video_texture) + ctx.drawImage(this._video_texture, 0, 0, this.size[0], this.size[1]); + } + ctx.restore(); } -} -ImageWebcam.prototype.onRemoved = function() -{ - this.closeStream(); -} - -ImageWebcam.prototype.streamReady = function(localMediaStream) -{ - this._webcam_stream = localMediaStream; - //this._waiting_confirmation = false; - this.boxcolor = "green"; - - var video = this._video; - if(!video) + LGraphTextureWebcam.prototype.onExecute = function() { - video = document.createElement("video"); - video.autoplay = true; - video.srcObject = localMediaStream; - this._video = video; - //document.body.appendChild( video ); //debug - //when video info is loaded (size and so) - video.onloadedmetadata = function(e) { - // Ready to go. Do some stuff. - console.log(e); + if(this._webcam_stream == null && !this._waiting_confirmation) + this.openStream(); + + if(!this._video || !this._video.videoWidth) + return; + + var width = this._video.videoWidth; + var height = this._video.videoHeight; + + var temp = this._video_texture; + if(!temp || temp.width != width || temp.height != height ) + this._video_texture = new GL.Texture( width, height, { format: gl.RGB, filter: gl.LINEAR }); + + this._video_texture.uploadImage( this._video ); + this._video_texture.version = ++this.version; + + if(this.properties.texture_name) + { + var container = LGraphTexture.getTexturesContainer(); + container[ this.properties.texture_name ] = this._video_texture; + } + + this.setOutputData(0,this._video_texture); + for(var i = 1; i < this.outputs.length; ++i) + { + if(!this.outputs[i]) + continue; + switch( this.outputs[i].name ) + { + case "width": this.setOutputData(i,this._video.videoWidth);break; + case "height": this.setOutputData(i,this._video.videoHeight);break; + } + } + } + + LGraphTextureWebcam.prototype.onGetOutputs = function() + { + return [["width","number"],["height","number"],["stream_ready",LiteGraph.EVENT],["stream_closed",LiteGraph.EVENT],["stream_error",LiteGraph.EVENT]]; + } + + LiteGraph.registerNodeType("texture/webcam", LGraphTextureWebcam ); + + + + //from https://github.com/spite/Wagner + function LGraphLensFX() + { + this.addInput("in","Texture"); + this.addInput("f","number"); + this.addOutput("out","Texture"); + this.properties = { enabled: true, factor: 1, precision: LGraphTexture.LOW }; + + this._uniforms = { u_texture: 0, u_factor: 1 }; + } + + LGraphLensFX.title = "Lens FX"; + LGraphLensFX.desc = "distortion and chromatic aberration"; + + LGraphLensFX.widgets_info = { + "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } + }; + + LGraphLensFX.prototype.onGetInputs = function() { return [["enabled","boolean"]]; } + + LGraphLensFX.prototype.onExecute = function() + { + var tex = this.getInputData(0); + if(!tex) + return; + + if(!this.isOutputConnected(0)) + return; //saves work + + if(this.properties.precision === LGraphTexture.PASS_THROUGH || this.getInputOrProperty("enabled" ) === false ) + { + this.setOutputData(0, tex ); + return; + } + + var temp = this._temp_texture; + if(!temp || temp.width != tex.width || temp.height != tex.height || temp.type != tex.type ) + temp = this._temp_texture = new GL.Texture( tex.width, tex.height, { type: tex.type, format: gl.RGBA, filter: gl.LINEAR }); + + var shader = LGraphLensFX._shader; + if(!shader) + shader = LGraphLensFX._shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphLensFX.pixel_shader ); + + var factor = this.getInputData(1); + if(factor == null) + factor = this.properties.factor; + + var uniforms = this._uniforms; + uniforms.u_factor = factor; + + //apply shader + gl.disable( gl.DEPTH_TEST ); + temp.drawTo(function(){ + tex.bind(0); + shader.uniforms(uniforms).draw( GL.Mesh.getScreenQuad() ); + }); + + this.setOutputData(0,temp); + } + + LGraphLensFX.pixel_shader = "precision highp float;\n\ + varying vec2 v_coord;\n\ + uniform sampler2D u_texture;\n\ + uniform float u_factor;\n\ + vec2 barrelDistortion(vec2 coord, float amt) {\n\ + vec2 cc = coord - 0.5;\n\ + float dist = dot(cc, cc);\n\ + return coord + cc * dist * amt;\n\ + }\n\ + \n\ + float sat( float t )\n\ + {\n\ + return clamp( t, 0.0, 1.0 );\n\ + }\n\ + \n\ + float linterp( float t ) {\n\ + return sat( 1.0 - abs( 2.0*t - 1.0 ) );\n\ + }\n\ + \n\ + float remap( float t, float a, float b ) {\n\ + return sat( (t - a) / (b - a) );\n\ + }\n\ + \n\ + vec4 spectrum_offset( float t ) {\n\ + vec4 ret;\n\ + float lo = step(t,0.5);\n\ + float hi = 1.0-lo;\n\ + float w = linterp( remap( t, 1.0/6.0, 5.0/6.0 ) );\n\ + ret = vec4(lo,1.0,hi, 1.) * vec4(1.0-w, w, 1.0-w, 1.);\n\ + \n\ + return pow( ret, vec4(1.0/2.2) );\n\ + }\n\ + \n\ + const float max_distort = 2.2;\n\ + const int num_iter = 12;\n\ + const float reci_num_iter_f = 1.0 / float(num_iter);\n\ + \n\ + void main()\n\ + { \n\ + vec2 uv=v_coord;\n\ + vec4 sumcol = vec4(0.0);\n\ + vec4 sumw = vec4(0.0); \n\ + for ( int i=0; ipixelcode must be vec3
\ -uvcode must be vec2, is optional
\ -uv: tex. coords
color: texture
colorB: textureB
time: scene time
value: input value
"; - - this.properties = {value:1, uvcode:"", pixelcode:"color + colorB * value", precision: LGraphTexture.DEFAULT }; - } - - LGraphTextureOperation.widgets_info = { - "uvcode": { widget:"textarea", height: 100 }, - "pixelcode": { widget:"textarea", height: 100 }, - "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } - }; - - LGraphTextureOperation.title = "Operation"; - LGraphTextureOperation.desc = "Texture shader operation"; - - LGraphTextureOperation.prototype.getExtraMenuOptions = function(graphcanvas) - { - var that = this; - var txt = !that.properties.show ? "Show Texture" : "Hide Texture"; - return [ {content: txt, callback: - function() { - that.properties.show = !that.properties.show; - } - }]; - } - - LGraphTextureOperation.prototype.onDrawBackground = function(ctx) - { - if(this.flags.collapsed || this.size[1] <= 20 || !this.properties.show) - return; - - if(!this._tex) - return; - - //only works if using a webgl renderer - if(this._tex.gl != ctx) - return; - - //render to graph canvas - ctx.save(); - ctx.drawImage(this._tex, 0, 0, this.size[0], this.size[1]); - ctx.restore(); - } - - LGraphTextureOperation.prototype.onExecute = function() - { - var tex = this.getInputData(0); - - if(!this.isOutputConnected(0)) - return; //saves work - - if(this.properties.precision === LGraphTexture.PASS_THROUGH) - { - this.setOutputData(0, tex); - return; - } - - var texB = this.getInputData(1); - - if(!this.properties.uvcode && !this.properties.pixelcode) - return; - - var width = 512; - var height = 512; - if(tex) - { - width = tex.width; - height = tex.height; - } - else if (texB) - { - width = texB.width; - height = texB.height; - } - - var type = LGraphTexture.getTextureType( this.properties.precision, tex ); - - if(!tex && !this._tex ) - this._tex = new GL.Texture( width, height, { type: type, format: gl.RGBA, filter: gl.LINEAR }); - else - this._tex = LGraphTexture.getTargetTexture( tex || this._tex, this._tex, this.properties.precision ); - - var uvcode = ""; - if(this.properties.uvcode) - { - uvcode = "uv = " + this.properties.uvcode; - if(this.properties.uvcode.indexOf(";") != -1) //there are line breaks, means multiline code - uvcode = this.properties.uvcode; - } - - var pixelcode = ""; - if(this.properties.pixelcode) - { - pixelcode = "result = " + this.properties.pixelcode; - if(this.properties.pixelcode.indexOf(";") != -1) //there are line breaks, means multiline code - pixelcode = this.properties.pixelcode; - } - - var shader = this._shader; - - if(!shader || this._shader_code != (uvcode + "|" + pixelcode) ) - { - try - { - this._shader = new GL.Shader(Shader.SCREEN_VERTEX_SHADER, LGraphTextureOperation.pixel_shader, { UV_CODE: uvcode, PIXEL_CODE: pixelcode }); - this.boxcolor = "#00FF00"; - } - catch (err) - { - console.log("Error compiling shader: ", err); - this.boxcolor = "#FF0000"; - return; - } - this.boxcolor = "#FF0000"; - - this._shader_code = (uvcode + "|" + pixelcode); - shader = this._shader; - } - - if(!shader) - { - this.boxcolor = "red"; - return; - } - else - this.boxcolor = "green"; - - var value = this.getInputData(2); - if(value != null) - this.properties.value = value; - else - value = parseFloat( this.properties.value ); - - var time = this.graph.getTime(); - - this._tex.drawTo(function() { - gl.disable( gl.DEPTH_TEST ); - gl.disable( gl.CULL_FACE ); - gl.disable( gl.BLEND ); - if(tex) tex.bind(0); - if(texB) texB.bind(1); - var mesh = Mesh.getScreenQuad(); - shader.uniforms({u_texture:0, u_textureB:1, value: value, texSize:[width,height], time: time}).draw(mesh); - }); - - this.setOutputData(0, this._tex); - } - - LGraphTextureOperation.pixel_shader = "precision highp float;\n\ - \n\ - uniform sampler2D u_texture;\n\ - uniform sampler2D u_textureB;\n\ - varying vec2 v_coord;\n\ - uniform vec2 texSize;\n\ - uniform float time;\n\ - uniform float value;\n\ - \n\ - void main() {\n\ - vec2 uv = v_coord;\n\ - UV_CODE;\n\ - vec4 color4 = texture2D(u_texture, uv);\n\ - vec3 color = color4.rgb;\n\ - vec4 color4B = texture2D(u_textureB, uv);\n\ - vec3 colorB = color4B.rgb;\n\ - vec3 result = color;\n\ - float alpha = 1.0;\n\ - PIXEL_CODE;\n\ - gl_FragColor = vec4(result, alpha);\n\ - }\n\ - "; - - LiteGraph.registerNodeType("texture/operation", LGraphTextureOperation ); - - //**************************************************** - - function LGraphTextureShader() - { - this.addOutput("out","Texture"); - this.properties = {code:"", width: 512, height: 512, precision: LGraphTexture.DEFAULT }; - - this.properties.code = "\nvoid main() {\n vec2 uv = v_coord;\n vec3 color = vec3(0.0);\n//your code here\n\ngl_FragColor = vec4(color, 1.0);\n}\n"; - this._uniforms = { in_texture:0, texSize: vec2.create(), time: 0 }; - } - - LGraphTextureShader.title = "Shader"; - LGraphTextureShader.desc = "Texture shader"; - LGraphTextureShader.widgets_info = { - "code": { type:"code" }, - "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } - }; - - LGraphTextureShader.prototype.onPropertyChanged = function(name, value) - { - if(name != "code") - return; - - var shader = this.getShader(); - if(!shader) - return; - - //update connections - var uniforms = shader.uniformInfo; - - //remove deprecated slots - if(this.inputs) - { - var already = {}; - for(var i = 0; i < this.inputs.length; ++i) - { - var info = this.getInputInfo(i); - if(!info) - continue; - - if( uniforms[ info.name ] && !already[ info.name ] ) - { - already[ info.name ] = true; - continue; - } - this.removeInput(i); - i--; - } - } - - //update existing ones - for(var i in uniforms) - { - var info = shader.uniformInfo[i]; - if(info.loc === null) - continue; //is an attribute, not a uniform - if(i == "time") //default one - continue; - - var type = "number"; - if( this._shader.samplers[i] ) - type = "texture"; - else - { - switch(info.size) - { - case 1: type = "number"; break; - case 2: type = "vec2"; break; - case 3: type = "vec3"; break; - case 4: type = "vec4"; break; - case 9: type = "mat3"; break; - case 16: type = "mat4"; break; - default: continue; - } - } - - var slot = this.findInputSlot(i); - if(slot == -1) - { - this.addInput(i,type); - continue; - } - - var input_info = this.getInputInfo(slot); - if(!input_info) - this.addInput(i,type); - else - { - if(input_info.type == type) - continue; - this.removeInput(slot,type); - this.addInput(i,type); - } - } - } - - LGraphTextureShader.prototype.getShader = function() - { - //replug - if(this._shader && this._shader_code == this.properties.code) - return this._shader; - - this._shader_code = this.properties.code; - this._shader = new GL.Shader(Shader.SCREEN_VERTEX_SHADER, LGraphTextureShader.pixel_shader + this.properties.code ); - if(!this._shader) { - this.boxcolor = "red"; - return null; - } - else - this.boxcolor = "green"; - return this._shader; - } - - LGraphTextureShader.prototype.onExecute = function() - { - if(!this.isOutputConnected(0)) - return; //saves work - - var shader = this.getShader(); - if(!shader) - return; - - var tex_slot = 0; - var in_tex = null; - - //set uniforms - for(var i = 0; i < this.inputs.length; ++i) - { - var info = this.getInputInfo(i); - var data = this.getInputData(i); - if(data == null) - continue; - - if(data.constructor === GL.Texture) - { - data.bind(tex_slot); - if(!in_tex) - in_tex = data; - data = tex_slot; - tex_slot++; - } - shader.setUniform( info.name, data ); //data is tex_slot - } - - var uniforms = this._uniforms; - var type = LGraphTexture.getTextureType( this.properties.precision, in_tex ); - - //render to texture - var w = this.properties.width|0; - var h = this.properties.height|0; - if(w == 0) - w = in_tex ? in_tex.width : gl.canvas.width; - if(h == 0) - h = in_tex ? in_tex.height : gl.canvas.height; - uniforms.texSize[0] = w; - uniforms.texSize[1] = h; - uniforms.time = this.graph.getTime(); - - if(!this._tex || this._tex.type != type || this._tex.width != w || this._tex.height != h ) - this._tex = new GL.Texture( w, h, { type: type, format: gl.RGBA, filter: gl.LINEAR }); - var tex = this._tex; - tex.drawTo(function() { - shader.uniforms( uniforms ).draw( GL.Mesh.getScreenQuad() ); - }); - - this.setOutputData( 0, this._tex ); - } - - LGraphTextureShader.pixel_shader = "precision highp float;\n\ - \n\ - varying vec2 v_coord;\n\ - uniform float time;\n\ - "; - - LiteGraph.registerNodeType("texture/shader", LGraphTextureShader ); - - // Texture Scale Offset - - function LGraphTextureScaleOffset() - { - this.addInput("in","Texture"); - this.addInput("scale","vec2"); - this.addInput("offset","vec2"); - this.addOutput("out","Texture"); - this.properties = { offset: vec2.fromValues(0,0), scale: vec2.fromValues(1,1), precision: LGraphTexture.DEFAULT }; - } - - LGraphTextureScaleOffset.widgets_info = { - "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } - }; - - LGraphTextureScaleOffset.title = "Scale/Offset"; - LGraphTextureScaleOffset.desc = "Applies an scaling and offseting"; - - LGraphTextureScaleOffset.prototype.onExecute = function() - { - var tex = this.getInputData(0); - - if(!this.isOutputConnected(0) || !tex) - return; //saves work - - if(this.properties.precision === LGraphTexture.PASS_THROUGH) - { - this.setOutputData(0, tex); - return; - } - - var width = tex.width; - var height = tex.height; - var type = this.precision === LGraphTexture.LOW ? gl.UNSIGNED_BYTE : gl.HIGH_PRECISION_FORMAT; - if (this.precision === LGraphTexture.DEFAULT) - type = tex.type; - - if(!this._tex || this._tex.width != width || this._tex.height != height || this._tex.type != type ) - this._tex = new GL.Texture( width, height, { type: type, format: gl.RGBA, filter: gl.LINEAR }); - - var shader = this._shader; - - if(!shader) - shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureScaleOffset.pixel_shader ); - - var scale = this.getInputData(1); - if(scale) - { - this.properties.scale[0] = scale[0]; - this.properties.scale[1] = scale[1]; - } - else - scale = this.properties.scale; - - var offset = this.getInputData(2); - if(offset) - { - this.properties.offset[0] = offset[0]; - this.properties.offset[1] = offset[1]; - } - else - offset = this.properties.offset; - - this._tex.drawTo(function() { - gl.disable( gl.DEPTH_TEST ); - gl.disable( gl.CULL_FACE ); - gl.disable( gl.BLEND ); - tex.bind(0); - var mesh = Mesh.getScreenQuad(); - shader.uniforms({u_texture:0, u_scale: scale, u_offset: offset}).draw( mesh ); - }); - - this.setOutputData( 0, this._tex ); - } - - LGraphTextureScaleOffset.pixel_shader = "precision highp float;\n\ - \n\ - uniform sampler2D u_texture;\n\ - uniform sampler2D u_textureB;\n\ - varying vec2 v_coord;\n\ - uniform vec2 u_scale;\n\ - uniform vec2 u_offset;\n\ - \n\ - void main() {\n\ - vec2 uv = v_coord;\n\ - uv = uv / u_scale - u_offset;\n\ - gl_FragColor = texture2D(u_texture, uv);\n\ - }\n\ - "; - - LiteGraph.registerNodeType("texture/scaleOffset", LGraphTextureScaleOffset ); - - - - // Warp (distort a texture) ************************* - - function LGraphTextureWarp() - { - this.addInput("in","Texture"); - this.addInput("warp","Texture"); - this.addInput("factor","number"); - this.addOutput("out","Texture"); - this.properties = { factor: 0.01, precision: LGraphTexture.DEFAULT }; - } - - LGraphTextureWarp.widgets_info = { - "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } - }; - - LGraphTextureWarp.title = "Warp"; - LGraphTextureWarp.desc = "Texture warp operation"; - - LGraphTextureWarp.prototype.onExecute = function() - { - var tex = this.getInputData(0); - - if(!this.isOutputConnected(0)) - return; //saves work - - if(this.properties.precision === LGraphTexture.PASS_THROUGH) - { - this.setOutputData(0, tex); - return; - } - - var texB = this.getInputData(1); - - var width = 512; - var height = 512; - var type = gl.UNSIGNED_BYTE; - if(tex) - { - width = tex.width; - height = tex.height; - type = tex.type; - } - else if (texB) - { - width = texB.width; - height = texB.height; - type = texB.type; - } - - if(!tex && !this._tex ) - this._tex = new GL.Texture( width, height, { type: this.precision === LGraphTexture.LOW ? gl.UNSIGNED_BYTE : gl.HIGH_PRECISION_FORMAT, format: gl.RGBA, filter: gl.LINEAR }); - else - this._tex = LGraphTexture.getTargetTexture( tex || this._tex, this._tex, this.properties.precision ); - - var shader = this._shader; - - if(!shader) - shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureWarp.pixel_shader ); - - var factor = this.getInputData(2); - if(factor != null) - this.properties.factor = factor; - else - factor = parseFloat( this.properties.factor ); - - this._tex.drawTo(function() { - gl.disable( gl.DEPTH_TEST ); - gl.disable( gl.CULL_FACE ); - gl.disable( gl.BLEND ); - if(tex) tex.bind(0); - if(texB) texB.bind(1); - var mesh = Mesh.getScreenQuad(); - shader.uniforms({u_texture:0, u_textureB:1, u_factor: factor }).draw( mesh ); - }); - - this.setOutputData(0, this._tex); - } - - LGraphTextureWarp.pixel_shader = "precision highp float;\n\ - \n\ - uniform sampler2D u_texture;\n\ - uniform sampler2D u_textureB;\n\ - varying vec2 v_coord;\n\ - uniform float u_factor;\n\ - \n\ - void main() {\n\ - vec2 uv = v_coord;\n\ - uv += ( texture2D(u_textureB, uv).rg - vec2(0.5)) * u_factor;\n\ - gl_FragColor = texture2D(u_texture, uv);\n\ - }\n\ - "; - - LiteGraph.registerNodeType("texture/warp", LGraphTextureWarp ); - - //**************************************************** - - // Texture to Viewport ***************************************** - function LGraphTextureToViewport() - { - this.addInput("Texture","Texture"); - this.properties = { additive: false, antialiasing: false, filter: true, disable_alpha: false, gamma: 1.0 }; - this.size[0] = 130; - } - - LGraphTextureToViewport.title = "to Viewport"; - LGraphTextureToViewport.desc = "Texture to viewport"; - - LGraphTextureToViewport.prototype.onExecute = function() - { - var tex = this.getInputData(0); - if(!tex) - return; - - if(this.properties.disable_alpha) - gl.disable( gl.BLEND ); - else - { - gl.enable( gl.BLEND ); - if(this.properties.additive) - gl.blendFunc( gl.SRC_ALPHA, gl.ONE ); - else - gl.blendFunc( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA ); - } - - gl.disable( gl.DEPTH_TEST ); - var gamma = this.properties.gamma || 1.0; - if( this.isInputConnected(1) ) - gamma = this.getInputData(1); - - tex.setParameter( gl.TEXTURE_MAG_FILTER, this.properties.filter ? gl.LINEAR : gl.NEAREST ); - - if(this.properties.antialiasing) - { - if(!LGraphTextureToViewport._shader) - LGraphTextureToViewport._shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureToViewport.aa_pixel_shader ); - - var viewport = gl.getViewport(); //gl.getParameter(gl.VIEWPORT); - var mesh = Mesh.getScreenQuad(); - tex.bind(0); - LGraphTextureToViewport._shader.uniforms({u_texture:0, uViewportSize:[tex.width,tex.height], u_igamma: 1 / gamma, inverseVP: [1/tex.width,1/tex.height] }).draw(mesh); - } - else - { - if(gamma != 1.0) - { - if(!LGraphTextureToViewport._gamma_shader) - LGraphTextureToViewport._gamma_shader = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureToViewport.gamma_pixel_shader ); - tex.toViewport(LGraphTextureToViewport._gamma_shader, { u_texture:0, u_igamma: 1 / gamma }); - } - else - tex.toViewport(); - } - } - - LGraphTextureToViewport.prototype.onGetInputs = function() - { - return [["gamma","number"]]; - } - - LGraphTextureToViewport.aa_pixel_shader = "precision highp float;\n\ - precision highp float;\n\ - varying vec2 v_coord;\n\ - uniform sampler2D u_texture;\n\ - uniform vec2 uViewportSize;\n\ - uniform vec2 inverseVP;\n\ - uniform float u_igamma;\n\ - #define FXAA_REDUCE_MIN (1.0/ 128.0)\n\ - #define FXAA_REDUCE_MUL (1.0 / 8.0)\n\ - #define FXAA_SPAN_MAX 8.0\n\ - \n\ - /* from mitsuhiko/webgl-meincraft based on the code on geeks3d.com */\n\ - vec4 applyFXAA(sampler2D tex, vec2 fragCoord)\n\ - {\n\ - vec4 color = vec4(0.0);\n\ - /*vec2 inverseVP = vec2(1.0 / uViewportSize.x, 1.0 / uViewportSize.y);*/\n\ - vec3 rgbNW = texture2D(tex, (fragCoord + vec2(-1.0, -1.0)) * inverseVP).xyz;\n\ - vec3 rgbNE = texture2D(tex, (fragCoord + vec2(1.0, -1.0)) * inverseVP).xyz;\n\ - vec3 rgbSW = texture2D(tex, (fragCoord + vec2(-1.0, 1.0)) * inverseVP).xyz;\n\ - vec3 rgbSE = texture2D(tex, (fragCoord + vec2(1.0, 1.0)) * inverseVP).xyz;\n\ - vec3 rgbM = texture2D(tex, fragCoord * inverseVP).xyz;\n\ - vec3 luma = vec3(0.299, 0.587, 0.114);\n\ - float lumaNW = dot(rgbNW, luma);\n\ - float lumaNE = dot(rgbNE, luma);\n\ - float lumaSW = dot(rgbSW, luma);\n\ - float lumaSE = dot(rgbSE, luma);\n\ - float lumaM = dot(rgbM, luma);\n\ - float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n\ - float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\ - \n\ - vec2 dir;\n\ - dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n\ - dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\ - \n\ - float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\ - \n\ - float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n\ - dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX), max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX), dir * rcpDirMin)) * inverseVP;\n\ - \n\ - vec3 rgbA = 0.5 * (texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz + \n\ - texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n\ - vec3 rgbB = rgbA * 0.5 + 0.25 * (texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz + \n\ - texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\ - \n\ - //return vec4(rgbA,1.0);\n\ - float lumaB = dot(rgbB, luma);\n\ - if ((lumaB < lumaMin) || (lumaB > lumaMax))\n\ - color = vec4(rgbA, 1.0);\n\ - else\n\ - color = vec4(rgbB, 1.0);\n\ - if(u_igamma != 1.0)\n\ - color.xyz = pow( color.xyz, vec3(u_igamma) );\n\ - return color;\n\ - }\n\ - \n\ - void main() {\n\ - gl_FragColor = applyFXAA( u_texture, v_coord * uViewportSize) ;\n\ - }\n\ - "; - - LGraphTextureToViewport.gamma_pixel_shader = "precision highp float;\n\ - precision highp float;\n\ - varying vec2 v_coord;\n\ - uniform sampler2D u_texture;\n\ - uniform float u_igamma;\n\ - void main() {\n\ - vec4 color = texture2D( u_texture, v_coord);\n\ - color.xyz = pow(color.xyz, vec3(u_igamma) );\n\ - gl_FragColor = color;\n\ - }\n\ - "; - - - LiteGraph.registerNodeType("texture/toviewport", LGraphTextureToViewport ); - - - // Texture Copy ***************************************** - function LGraphTextureCopy() - { - this.addInput("Texture","Texture"); - this.addOutput("","Texture"); - this.properties = { size: 0, generate_mipmaps: false, precision: LGraphTexture.DEFAULT }; - } - - LGraphTextureCopy.title = "Copy"; - LGraphTextureCopy.desc = "Copy Texture"; - LGraphTextureCopy.widgets_info = { - size: { widget:"combo", values:[0,32,64,128,256,512,1024,2048]}, - precision: { widget:"combo", values: LGraphTexture.MODE_VALUES } - }; - - LGraphTextureCopy.prototype.onExecute = function() - { - var tex = this.getInputData(0); - if(!tex && !this._temp_texture) - return; - - if(!this.isOutputConnected(0)) - return; //saves work - - //copy the texture - if(tex) - { - var width = tex.width; - var height = tex.height; - - if(this.properties.size != 0) - { - width = this.properties.size; - height = this.properties.size; - } - - var temp = this._temp_texture; - - var type = tex.type; - if(this.properties.precision === LGraphTexture.LOW) - type = gl.UNSIGNED_BYTE; - else if(this.properties.precision === LGraphTexture.HIGH) - type = gl.HIGH_PRECISION_FORMAT; - - if(!temp || temp.width != width || temp.height != height || temp.type != type ) - { - var minFilter = gl.LINEAR; - if( this.properties.generate_mipmaps && isPowerOfTwo(width) && isPowerOfTwo(height) ) - minFilter = gl.LINEAR_MIPMAP_LINEAR; - this._temp_texture = new GL.Texture( width, height, { type: type, format: gl.RGBA, minFilter: minFilter, magFilter: gl.LINEAR }); - } - tex.copyTo(this._temp_texture); - - if(this.properties.generate_mipmaps) - { - this._temp_texture.bind(0); - gl.generateMipmap(this._temp_texture.texture_type); - this._temp_texture.unbind(0); - } - } - - - this.setOutputData(0,this._temp_texture); - } - - LiteGraph.registerNodeType("texture/copy", LGraphTextureCopy ); - - - // Texture Downsample ***************************************** - function LGraphTextureDownsample() - { - this.addInput("Texture","Texture"); - this.addOutput("","Texture"); - this.properties = { iterations: 1, generate_mipmaps: false, precision: LGraphTexture.DEFAULT }; - } - - LGraphTextureDownsample.title = "Downsample"; - LGraphTextureDownsample.desc = "Downsample Texture"; - LGraphTextureDownsample.widgets_info = { - iterations: { type:"number", step: 1, precision: 0, min: 1 }, - precision: { widget:"combo", values: LGraphTexture.MODE_VALUES } - }; - - LGraphTextureDownsample.prototype.onExecute = function() - { - var tex = this.getInputData(0); - if(!tex && !this._temp_texture) - return; - - if(!this.isOutputConnected(0)) - return; //saves work - - //we do not allow any texture different than texture 2D - if(!tex || tex.texture_type !== GL.TEXTURE_2D ) - return; - - var shader = LGraphTextureDownsample._shader; - if(!shader) - LGraphTextureDownsample._shader = shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureDownsample.pixel_shader ); - - var width = tex.width|0; - var height = tex.height|0; - var type = tex.type; - if(this.properties.precision === LGraphTexture.LOW) - type = gl.UNSIGNED_BYTE; - else if(this.properties.precision === LGraphTexture.HIGH) - type = gl.HIGH_PRECISION_FORMAT; - var iterations = this.properties.iterations || 1; - - var origin = tex; - var target = null; - - var temp = []; - var options = { - type: type, - format: tex.format - }; - - var offset = vec2.create(); - var uniforms = { - u_offset: offset - }; - - if( this._texture ) - GL.Texture.releaseTemporary( this._texture ); - - for(var i = 0; i < iterations; ++i) - { - offset[0] = 1/width; - offset[1] = 1/height; - width = width>>1 || 0; - height = height>>1 || 0; - target = GL.Texture.getTemporary( width, height, options ); - temp.push( target ); - origin.setParameter( GL.TEXTURE_MAG_FILTER, GL.NEAREST ); - origin.copyTo( target, shader, uniforms ); - if(width == 1 && height == 1) - break; //nothing else to do - origin = target; - } - - //keep the last texture used - this._texture = temp.pop(); - - //free the rest - for(var i = 0; i < temp.length; ++i) - GL.Texture.releaseTemporary( temp[i] ); - - if(this.properties.generate_mipmaps) - { - this._texture.bind(0); - gl.generateMipmap(this._texture.texture_type); - this._texture.unbind(0); - } - - this.setOutputData(0,this._texture); - } - - LGraphTextureDownsample.pixel_shader = "precision highp float;\n\ - precision highp float;\n\ - uniform sampler2D u_texture;\n\ - uniform vec2 u_offset;\n\ - varying vec2 v_coord;\n\ - \n\ - void main() {\n\ - vec4 color = texture2D(u_texture, v_coord );\n\ - color += texture2D(u_texture, v_coord + vec2( u_offset.x, 0.0 ) );\n\ - color += texture2D(u_texture, v_coord + vec2( 0.0, u_offset.y ) );\n\ - color += texture2D(u_texture, v_coord + vec2( u_offset.x, u_offset.y ) );\n\ - gl_FragColor = color * 0.25;\n\ - }\n\ - "; - - LiteGraph.registerNodeType("texture/downsample", LGraphTextureDownsample ); - - - - // Texture Copy ***************************************** - function LGraphTextureAverage() - { - this.addInput("Texture","Texture"); - this.addOutput("tex","Texture"); - this.addOutput("avg","vec4"); - this.addOutput("lum","number"); - this.properties = { mipmap_offset: 0, low_precision: false }; - - this._uniforms = { u_texture: 0, u_mipmap_offset: this.properties.mipmap_offset }; - this._luminance = new Float32Array(4); - } - - LGraphTextureAverage.title = "Average"; - LGraphTextureAverage.desc = "Compute a partial average (32 random samples) of a texture and stores it as a 1x1 pixel texture"; - - LGraphTextureAverage.prototype.onExecute = function() - { - var tex = this.getInputData(0); - if(!tex) - return; - - if(!this.isOutputConnected(0) && !this.isOutputConnected(1) && !this.isOutputConnected(2)) - return; //saves work - - if(!LGraphTextureAverage._shader) - { - LGraphTextureAverage._shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureAverage.pixel_shader); - //creates 32 random numbers and stores the, in two mat4 - var samples = new Float32Array(32); - for(var i = 0; i < 32; ++i) - samples[i] = Math.random(); - LGraphTextureAverage._shader.uniforms({u_samples_a: samples.subarray(0,16), u_samples_b: samples.subarray(16,32) }); - } - - var temp = this._temp_texture; - var type = gl.UNSIGNED_BYTE; - if(tex.type != type) //force floats, half floats cannot be read with gl.readPixels - type = gl.FLOAT; - - if(!temp || temp.type != type ) - this._temp_texture = new GL.Texture( 1, 1, { type: type, format: gl.RGBA, filter: gl.NEAREST }); - - var shader = LGraphTextureAverage._shader; - var uniforms = this._uniforms; - uniforms.u_mipmap_offset = this.properties.mipmap_offset; - this._temp_texture.drawTo(function(){ - tex.toViewport( shader, uniforms ); - }); - - this.setOutputData(0,this._temp_texture); - - if(this.isOutputConnected(1) || this.isOutputConnected(2)) - { - var pixel = this._temp_texture.getPixels(); - if(pixel) - { - var v = this._luminance; - var type = this._temp_texture.type; - v.set( pixel ); - if(type == gl.UNSIGNED_BYTE) - vec4.scale( v,v, 1/255 ); - else if(type == GL.HALF_FLOAT || type == GL.HALF_FLOAT_OES) - vec4.scale( v,v, 1/(255*255) ); //is this correct? - this.setOutputData(1,v); - this.setOutputData(2,(v[0] + v[1] + v[2]) / 3); - } - - } - } - - LGraphTextureAverage.pixel_shader = "precision highp float;\n\ - precision highp float;\n\ - uniform mat4 u_samples_a;\n\ - uniform mat4 u_samples_b;\n\ - uniform sampler2D u_texture;\n\ - uniform float u_mipmap_offset;\n\ - varying vec2 v_coord;\n\ - \n\ - void main() {\n\ - vec4 color = vec4(0.0);\n\ - for(int i = 0; i < 4; ++i)\n\ - for(int j = 0; j < 4; ++j)\n\ - {\n\ - color += texture2D(u_texture, vec2( u_samples_a[i][j], u_samples_b[i][j] ), u_mipmap_offset );\n\ - color += texture2D(u_texture, vec2( 1.0 - u_samples_a[i][j], 1.0 - u_samples_b[i][j] ), u_mipmap_offset );\n\ - }\n\ - gl_FragColor = color * 0.03125;\n\ - }\n\ - "; - - LiteGraph.registerNodeType("texture/average", LGraphTextureAverage ); - - // Image To Texture ***************************************** - function LGraphImageToTexture() - { - this.addInput("Image","image"); - this.addOutput("","Texture"); - this.properties = {}; - } - - LGraphImageToTexture.title = "Image to Texture"; - LGraphImageToTexture.desc = "Uploads an image to the GPU"; - //LGraphImageToTexture.widgets_info = { size: { widget:"combo", values:[0,32,64,128,256,512,1024,2048]} }; - - LGraphImageToTexture.prototype.onExecute = function() - { - var img = this.getInputData(0); - if(!img) - return; - - var width = img.videoWidth || img.width; - var height = img.videoHeight || img.height; - - //this is in case we are using a webgl canvas already, no need to reupload it - if(img.gltexture) - { - this.setOutputData(0,img.gltexture); - return; - } - - - var temp = this._temp_texture; - if(!temp || temp.width != width || temp.height != height ) - this._temp_texture = new GL.Texture( width, height, { format: gl.RGBA, filter: gl.LINEAR }); - - try - { - this._temp_texture.uploadImage(img); - } - catch(err) - { - console.error("image comes from an unsafe location, cannot be uploaded to webgl: " + err); - return; - } - - this.setOutputData(0,this._temp_texture); - } - - LiteGraph.registerNodeType("texture/imageToTexture", LGraphImageToTexture ); - - - // Texture LUT ***************************************** - function LGraphTextureLUT() - { - this.addInput("Texture","Texture"); - this.addInput("LUT","Texture"); - this.addInput("Intensity","number"); - this.addOutput("","Texture"); - this.properties = { intensity: 1, precision: LGraphTexture.DEFAULT, texture: null }; - - if(!LGraphTextureLUT._shader) - LGraphTextureLUT._shader = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureLUT.pixel_shader ); - } - - LGraphTextureLUT.widgets_info = { - "texture": { widget:"texture"}, - "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } - }; - - LGraphTextureLUT.title = "LUT"; - LGraphTextureLUT.desc = "Apply LUT to Texture"; - - LGraphTextureLUT.prototype.onExecute = function() - { - if(!this.isOutputConnected(0)) - return; //saves work - - var tex = this.getInputData(0); - - if(this.properties.precision === LGraphTexture.PASS_THROUGH ) - { - this.setOutputData(0,tex); - return; - } - - if(!tex) - return; - - var lut_tex = this.getInputData(1); - - if(!lut_tex) - lut_tex = LGraphTexture.getTexture( this.properties.texture ); - - if(!lut_tex) - { - this.setOutputData(0,tex); - return; - } - - lut_tex.bind(0); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR ); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); - gl.bindTexture(gl.TEXTURE_2D, null); - - var intensity = this.properties.intensity; - if( this.isInputConnected(2) ) - this.properties.intensity = intensity = this.getInputData(2); - - this._tex = LGraphTexture.getTargetTexture( tex, this._tex, this.properties.precision ); - - //var mesh = Mesh.getScreenQuad(); - - this._tex.drawTo(function() { - lut_tex.bind(1); - tex.toViewport( LGraphTextureLUT._shader, {u_texture:0, u_textureB:1, u_amount: intensity} ); - }); - - this.setOutputData(0,this._tex); - } - - LGraphTextureLUT.pixel_shader = "precision highp float;\n\ - precision highp float;\n\ - varying vec2 v_coord;\n\ - uniform sampler2D u_texture;\n\ - uniform sampler2D u_textureB;\n\ - uniform float u_amount;\n\ - \n\ - void main() {\n\ - lowp vec4 textureColor = clamp( texture2D(u_texture, v_coord), vec4(0.0), vec4(1.0) );\n\ - mediump float blueColor = textureColor.b * 63.0;\n\ - mediump vec2 quad1;\n\ - quad1.y = floor(floor(blueColor) / 8.0);\n\ - quad1.x = floor(blueColor) - (quad1.y * 8.0);\n\ - mediump vec2 quad2;\n\ - quad2.y = floor(ceil(blueColor) / 8.0);\n\ - quad2.x = ceil(blueColor) - (quad2.y * 8.0);\n\ - highp vec2 texPos1;\n\ - texPos1.x = (quad1.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);\n\ - texPos1.y = 1.0 - ((quad1.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g));\n\ - highp vec2 texPos2;\n\ - texPos2.x = (quad2.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);\n\ - texPos2.y = 1.0 - ((quad2.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g));\n\ - lowp vec4 newColor1 = texture2D(u_textureB, texPos1);\n\ - lowp vec4 newColor2 = texture2D(u_textureB, texPos2);\n\ - lowp vec4 newColor = mix(newColor1, newColor2, fract(blueColor));\n\ - gl_FragColor = vec4( mix( textureColor.rgb, newColor.rgb, u_amount), textureColor.w);\n\ - }\n\ - "; - - LiteGraph.registerNodeType("texture/LUT", LGraphTextureLUT ); - - // Texture Channels ***************************************** - function LGraphTextureChannels() - { - this.addInput("Texture","Texture"); - - this.addOutput("R","Texture"); - this.addOutput("G","Texture"); - this.addOutput("B","Texture"); - this.addOutput("A","Texture"); - - this.properties = {}; - if(!LGraphTextureChannels._shader) - LGraphTextureChannels._shader = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureChannels.pixel_shader ); - } - - LGraphTextureChannels.title = "Texture to Channels"; - LGraphTextureChannels.desc = "Split texture channels"; - - LGraphTextureChannels.prototype.onExecute = function() - { - var texA = this.getInputData(0); - if(!texA) return; - - if(!this._channels) - this._channels = Array(4); - - var connections = 0; - for(var i = 0; i < 4; i++) - { - if(this.isOutputConnected(i)) - { - if(!this._channels[i] || this._channels[i].width != texA.width || this._channels[i].height != texA.height || this._channels[i].type != texA.type) - this._channels[i] = new GL.Texture( texA.width, texA.height, { type: texA.type, format: gl.RGBA, filter: gl.LINEAR }); - connections++; - } - else - this._channels[i] = null; - } - - if(!connections) - return; - - gl.disable( gl.BLEND ); - gl.disable( gl.DEPTH_TEST ); - - var mesh = Mesh.getScreenQuad(); - var shader = LGraphTextureChannels._shader; - var masks = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]; - - for(var i = 0; i < 4; i++) - { - if(!this._channels[i]) - continue; - - this._channels[i].drawTo( function() { - texA.bind(0); - shader.uniforms({u_texture:0, u_mask: masks[i]}).draw(mesh); - }); - this.setOutputData(i, this._channels[i]); - } - } - - LGraphTextureChannels.pixel_shader = "precision highp float;\n\ - precision highp float;\n\ - varying vec2 v_coord;\n\ - uniform sampler2D u_texture;\n\ - uniform vec4 u_mask;\n\ - \n\ - void main() {\n\ - gl_FragColor = vec4( vec3( length( texture2D(u_texture, v_coord) * u_mask )), 1.0 );\n\ - }\n\ - "; - - LiteGraph.registerNodeType("texture/textureChannels", LGraphTextureChannels ); - - - // Texture Channels to Texture ***************************************** - function LGraphChannelsTexture() - { - this.addInput("R","Texture"); - this.addInput("G","Texture"); - this.addInput("B","Texture"); - this.addInput("A","Texture"); - - this.addOutput("Texture","Texture"); - - this.properties = {}; - if(!LGraphChannelsTexture._shader) - LGraphChannelsTexture._shader = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphChannelsTexture.pixel_shader ); - } - - LGraphChannelsTexture.title = "Channels to Texture"; - LGraphChannelsTexture.desc = "Split texture channels"; - - LGraphChannelsTexture.prototype.onExecute = function() - { - var tex = [ this.getInputData(0), - this.getInputData(1), - this.getInputData(2), - this.getInputData(3) ]; - - if(!tex[0] || !tex[1] || !tex[2] || !tex[3]) - return; - - gl.disable( gl.BLEND ); - gl.disable( gl.DEPTH_TEST ); - - var mesh = Mesh.getScreenQuad(); - var shader = LGraphChannelsTexture._shader; - - this._tex = LGraphTexture.getTargetTexture( tex[0], this._tex ); - - this._tex.drawTo( function() { - tex[0].bind(0); - tex[1].bind(1); - tex[2].bind(2); - tex[3].bind(3); - shader.uniforms({u_textureR:0, u_textureG:1, u_textureB:2, u_textureA:3 }).draw(mesh); - }); - this.setOutputData(0, this._tex); - } - - LGraphChannelsTexture.pixel_shader = "precision highp float;\n\ - precision highp float;\n\ - varying vec2 v_coord;\n\ - uniform sampler2D u_textureR;\n\ - uniform sampler2D u_textureG;\n\ - uniform sampler2D u_textureB;\n\ - uniform sampler2D u_textureA;\n\ - \n\ - void main() {\n\ - gl_FragColor = vec4( \ - texture2D(u_textureR, v_coord).r,\ - texture2D(u_textureG, v_coord).r,\ - texture2D(u_textureB, v_coord).r,\ - texture2D(u_textureA, v_coord).r);\n\ - }\n\ - "; - - LiteGraph.registerNodeType("texture/channelsTexture", LGraphChannelsTexture ); - - // Texture Color ***************************************** - function LGraphTextureColor() - { - this.addOutput("Texture","Texture"); - - this._tex_color = vec4.create(); - this.properties = { color: vec4.create(), precision: LGraphTexture.DEFAULT }; - } - - LGraphTextureColor.title = "Color"; - LGraphTextureColor.desc = "Generates a 1x1 texture with a constant color"; - - LGraphTextureColor.widgets_info = { - "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } - }; - - LGraphTextureColor.prototype.onDrawBackground = function( ctx ) - { - var c = this.properties.color; - ctx.fillStyle = "rgb(" + Math.floor(Math.clamp(c[0],0,1)*255) + "," + Math.floor(Math.clamp(c[1],0,1)*255) + "," + Math.floor(Math.clamp(c[2],0,1)*255) + ")"; - if(this.flags.collapsed) - this.boxcolor = ctx.fillStyle; - else - ctx.fillRect(0,0,this.size[0],this.size[1]); - } - - LGraphTextureColor.prototype.onExecute = function() - { - var type = this.properties.precision == LGraphTexture.HIGH ? LGraphTexture.HIGH_PRECISION_FORMAT : gl.UNSIGNED_BYTE; - - if(!this._tex || this._tex.type != type ) - this._tex = new GL.Texture(1,1,{ format: gl.RGBA, type: type, minFilter: gl.NEAREST }); - var color = this.properties.color; - - if(this.inputs) - for(var i = 0; i < this.inputs.length; i++) - { - var input = this.inputs[i]; - var v = this.getInputData(i); - if(v === undefined) - continue; - switch(input.name) - { - case 'RGB': - case 'RGBA': - color.set(v); - break; - case 'R': color[0] = v; break; - case 'G': color[1] = v; break; - case 'B': color[2] = v; break; - case 'A': color[3] = v; break; - } - } - - if( vec4.sqrDist( this._tex_color, color) > 0.001 ) - { - this._tex_color.set( color ); - this._tex.fill( color ); - } - this.setOutputData(0, this._tex); - } - - LGraphTextureColor.prototype.onGetInputs = function() - { - return [["RGB","vec3"],["RGBA","vec4"],["R","number"],["G","number"],["B","number"],["A","number"]]; - } - - LiteGraph.registerNodeType("texture/color", LGraphTextureColor ); - - // Texture Channels to Texture ***************************************** - function LGraphTextureGradient() - { - this.addInput("A","color"); - this.addInput("B","color"); - this.addOutput("Texture","Texture"); - - this.properties = { angle: 0, scale: 1, A:[0,0,0], B:[1,1,1], texture_size:32 }; - if(!LGraphTextureGradient._shader) - LGraphTextureGradient._shader = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureGradient.pixel_shader ); - - this._uniforms = { u_angle: 0, u_colorA: vec3.create(), u_colorB: vec3.create()}; - } - - LGraphTextureGradient.title = "Gradient"; - LGraphTextureGradient.desc = "Generates a gradient"; - LGraphTextureGradient["@A"] = { type:"color" }; - LGraphTextureGradient["@B"] = { type:"color" }; - LGraphTextureGradient["@texture_size"] = { type:"enum", values:[32,64,128,256,512] }; - - LGraphTextureGradient.prototype.onExecute = function() - { - gl.disable( gl.BLEND ); - gl.disable( gl.DEPTH_TEST ); - - var mesh = GL.Mesh.getScreenQuad(); - var shader = LGraphTextureGradient._shader; - - var A = this.getInputData(0); - if(!A) - A = this.properties.A; - var B = this.getInputData(1); - if(!B) - B = this.properties.B; - - //angle and scale - for(var i = 2; i < this.inputs.length; i++) - { - var input = this.inputs[i]; - var v = this.getInputData(i); - if(v === undefined) - continue; - this.properties[ input.name ] = v; - } - - var uniforms = this._uniforms; - this._uniforms.u_angle = this.properties.angle * DEG2RAD; - this._uniforms.u_scale = this.properties.scale; - vec3.copy( uniforms.u_colorA, A ); - vec3.copy( uniforms.u_colorB, B ); - - var size = parseInt( this.properties.texture_size ); - if(!this._tex || this._tex.width != size ) - this._tex = new GL.Texture( size, size, { format: gl.RGB, filter: gl.LINEAR }); - - this._tex.drawTo( function() { - shader.uniforms(uniforms).draw(mesh); - }); - this.setOutputData(0, this._tex); - } - - LGraphTextureGradient.prototype.onGetInputs = function() - { - return [["angle","number"],["scale","number"]]; - } - - LGraphTextureGradient.pixel_shader = "precision highp float;\n\ - precision highp float;\n\ - varying vec2 v_coord;\n\ - uniform float u_angle;\n\ - uniform float u_scale;\n\ - uniform vec3 u_colorA;\n\ - uniform vec3 u_colorB;\n\ - \n\ - vec2 rotate(vec2 v, float angle)\n\ - {\n\ - vec2 result;\n\ - float _cos = cos(angle);\n\ - float _sin = sin(angle);\n\ - result.x = v.x * _cos - v.y * _sin;\n\ - result.y = v.x * _sin + v.y * _cos;\n\ - return result;\n\ - }\n\ - void main() {\n\ - float f = (rotate(u_scale * (v_coord - vec2(0.5)), u_angle) + vec2(0.5)).x;\n\ - vec3 color = mix(u_colorA,u_colorB,clamp(f,0.0,1.0));\n\ - gl_FragColor = vec4(color,1.0);\n\ - }\n\ - "; - - LiteGraph.registerNodeType("texture/gradient", LGraphTextureGradient ); - - // Texture Mix ***************************************** - function LGraphTextureMix() - { - this.addInput("A","Texture"); - this.addInput("B","Texture"); - this.addInput("Mixer","Texture"); - - this.addOutput("Texture","Texture"); - this.properties = { factor: 0.5, precision: LGraphTexture.DEFAULT }; - this._uniforms = { u_textureA:0, u_textureB:1, u_textureMix:2, u_mix: vec4.create() }; - } - - LGraphTextureMix.title = "Mix"; - LGraphTextureMix.desc = "Generates a texture mixing two textures"; - - LGraphTextureMix.widgets_info = { - "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } - }; - - LGraphTextureMix.prototype.onExecute = function() - { - var texA = this.getInputData(0); - - if(!this.isOutputConnected(0)) - return; //saves work - - if(this.properties.precision === LGraphTexture.PASS_THROUGH ) - { - this.setOutputData(0,texA); - return; - } - - var texB = this.getInputData(1); - if(!texA || !texB ) - return; - - var texMix = this.getInputData(2); - - var factor = this.getInputData(3); - - - this._tex = LGraphTexture.getTargetTexture( texA, this._tex, this.properties.precision ); - - gl.disable( gl.BLEND ); - gl.disable( gl.DEPTH_TEST ); - - var mesh = Mesh.getScreenQuad(); - var shader = null; - var uniforms = this._uniforms; - if(texMix) - { - shader = LGraphTextureMix._shader_tex; - if(!shader) - shader = LGraphTextureMix._shader_tex = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureMix.pixel_shader, {"MIX_TEX":""}); - } - else - { - shader = LGraphTextureMix._shader_factor; - if(!shader) - shader = LGraphTextureMix._shader_factor = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureMix.pixel_shader ); - var f = factor == null ? this.properties.factor : factor; - uniforms.u_mix.set([f,f,f,f]); - } - - this._tex.drawTo( function() { - texA.bind(0); - texB.bind(1); - if(texMix) - texMix.bind(2); - shader.uniforms( uniforms ).draw(mesh); - }); - - this.setOutputData(0, this._tex); - } - - LGraphTextureMix.prototype.onGetInputs = function() - { - return [["factor","number"]]; - } - - LGraphTextureMix.pixel_shader = "precision highp float;\n\ - precision highp float;\n\ - varying vec2 v_coord;\n\ - uniform sampler2D u_textureA;\n\ - uniform sampler2D u_textureB;\n\ - #ifdef MIX_TEX\n\ - uniform sampler2D u_textureMix;\n\ - #else\n\ - uniform vec4 u_mix;\n\ - #endif\n\ - \n\ - void main() {\n\ - #ifdef MIX_TEX\n\ - vec4 f = texture2D(u_textureMix, v_coord);\n\ - #else\n\ - vec4 f = u_mix;\n\ - #endif\n\ - gl_FragColor = mix( texture2D(u_textureA, v_coord), texture2D(u_textureB, v_coord), f );\n\ - }\n\ - "; - - LiteGraph.registerNodeType("texture/mix", LGraphTextureMix ); - - // Texture Edges detection ***************************************** - function LGraphTextureEdges() - { - this.addInput("Tex.","Texture"); - - this.addOutput("Edges","Texture"); - this.properties = { invert: true, threshold: false, factor: 1, precision: LGraphTexture.DEFAULT }; - - if(!LGraphTextureEdges._shader) - LGraphTextureEdges._shader = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureEdges.pixel_shader ); - } - - LGraphTextureEdges.title = "Edges"; - LGraphTextureEdges.desc = "Detects edges"; - - LGraphTextureEdges.widgets_info = { - "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } - }; - - LGraphTextureEdges.prototype.onExecute = function() - { - if(!this.isOutputConnected(0)) - return; //saves work - - var tex = this.getInputData(0); - - if(this.properties.precision === LGraphTexture.PASS_THROUGH ) - { - this.setOutputData(0,tex); - return; - } - - if(!tex) return; - - this._tex = LGraphTexture.getTargetTexture( tex, this._tex, this.properties.precision ); - - gl.disable( gl.BLEND ); - gl.disable( gl.DEPTH_TEST ); - - var mesh = Mesh.getScreenQuad(); - var shader = LGraphTextureEdges._shader; - var invert = this.properties.invert; - var factor = this.properties.factor; - var threshold = this.properties.threshold ? 1 : 0; - - this._tex.drawTo( function() { - tex.bind(0); - shader.uniforms({u_texture:0, u_isize:[1/tex.width,1/tex.height], u_factor: factor, u_threshold: threshold, u_invert: invert ? 1 : 0}).draw(mesh); - }); - - this.setOutputData(0, this._tex); - } - - LGraphTextureEdges.pixel_shader = "precision highp float;\n\ - precision highp float;\n\ - varying vec2 v_coord;\n\ - uniform sampler2D u_texture;\n\ - uniform vec2 u_isize;\n\ - uniform int u_invert;\n\ - uniform float u_factor;\n\ - uniform float u_threshold;\n\ - \n\ - void main() {\n\ - vec4 center = texture2D(u_texture, v_coord);\n\ - vec4 up = texture2D(u_texture, v_coord + u_isize * vec2(0.0,1.0) );\n\ - vec4 down = texture2D(u_texture, v_coord + u_isize * vec2(0.0,-1.0) );\n\ - vec4 left = texture2D(u_texture, v_coord + u_isize * vec2(1.0,0.0) );\n\ - vec4 right = texture2D(u_texture, v_coord + u_isize * vec2(-1.0,0.0) );\n\ - vec4 diff = abs(center - up) + abs(center - down) + abs(center - left) + abs(center - right);\n\ - diff *= u_factor;\n\ - if(u_invert == 1)\n\ - diff.xyz = vec3(1.0) - diff.xyz;\n\ - if( u_threshold == 0.0 )\n\ - gl_FragColor = vec4( diff.xyz, center.a );\n\ - else\n\ - gl_FragColor = vec4( diff.x > 0.5 ? 1.0 : 0.0, diff.y > 0.5 ? 1.0 : 0.0, diff.z > 0.5 ? 1.0 : 0.0, center.a );\n\ - }\n\ - "; - - LiteGraph.registerNodeType("texture/edges", LGraphTextureEdges ); - - // Texture Depth ***************************************** - function LGraphTextureDepthRange() - { - this.addInput("Texture","Texture"); - this.addInput("Distance","number"); - this.addInput("Range","number"); - this.addOutput("Texture","Texture"); - this.properties = { distance:100, range: 50, only_depth: false, high_precision: false }; - this._uniforms = {u_texture:0, u_distance: 100, u_range: 50, u_camera_planes: null }; - } - - LGraphTextureDepthRange.title = "Depth Range"; - LGraphTextureDepthRange.desc = "Generates a texture with a depth range"; - - LGraphTextureDepthRange.prototype.onExecute = function() - { - if(!this.isOutputConnected(0)) - return; //saves work - - var tex = this.getInputData(0); - if(!tex) return; - - var precision = gl.UNSIGNED_BYTE; - if(this.properties.high_precision) - precision = gl.half_float_ext ? gl.HALF_FLOAT_OES : gl.FLOAT; - - if(!this._temp_texture || this._temp_texture.type != precision || - this._temp_texture.width != tex.width || this._temp_texture.height != tex.height) - this._temp_texture = new GL.Texture( tex.width, tex.height, { type: precision, format: gl.RGBA, filter: gl.LINEAR }); - - var uniforms = this._uniforms; - - //iterations - var distance = this.properties.distance; - if( this.isInputConnected(1) ) - { - distance = this.getInputData(1); - this.properties.distance = distance; - } - - var range = this.properties.range; - if( this.isInputConnected(2) ) - { - range = this.getInputData(2); - this.properties.range = range; - } - - uniforms.u_distance = distance; - uniforms.u_range = range; - - gl.disable( gl.BLEND ); - gl.disable( gl.DEPTH_TEST ); - var mesh = Mesh.getScreenQuad(); - if(!LGraphTextureDepthRange._shader) - { - LGraphTextureDepthRange._shader = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureDepthRange.pixel_shader ); - LGraphTextureDepthRange._shader_onlydepth = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureDepthRange.pixel_shader, { ONLY_DEPTH:""} ); - } - var shader = this.properties.only_depth ? LGraphTextureDepthRange._shader_onlydepth : LGraphTextureDepthRange._shader; - - //NEAR AND FAR PLANES - var planes = null; - if( tex.near_far_planes ) - planes = tex.near_far_planes; - else if( window.LS && LS.Renderer._main_camera ) - planes = LS.Renderer._main_camera._uniforms.u_camera_planes; - else - planes = [0.1,1000]; //hardcoded - uniforms.u_camera_planes = planes; - - - this._temp_texture.drawTo( function() { - tex.bind(0); - shader.uniforms( uniforms ).draw(mesh); - }); - - this._temp_texture.near_far_planes = planes; - this.setOutputData(0, this._temp_texture ); - } - - LGraphTextureDepthRange.pixel_shader = "precision highp float;\n\ - precision highp float;\n\ - varying vec2 v_coord;\n\ - uniform sampler2D u_texture;\n\ - uniform vec2 u_camera_planes;\n\ - uniform float u_distance;\n\ - uniform float u_range;\n\ - \n\ - float LinearDepth()\n\ - {\n\ - float zNear = u_camera_planes.x;\n\ - float zFar = u_camera_planes.y;\n\ - float depth = texture2D(u_texture, v_coord).x;\n\ - depth = depth * 2.0 - 1.0;\n\ - return zNear * (depth + 1.0) / (zFar + zNear - depth * (zFar - zNear));\n\ - }\n\ - \n\ - void main() {\n\ - float depth = LinearDepth();\n\ - #ifdef ONLY_DEPTH\n\ - gl_FragColor = vec4(depth);\n\ - #else\n\ - float diff = abs(depth * u_camera_planes.y - u_distance);\n\ - float dof = 1.0;\n\ - if(diff <= u_range)\n\ - dof = diff / u_range;\n\ - gl_FragColor = vec4(dof);\n\ - #endif\n\ - }\n\ - "; - - LiteGraph.registerNodeType("texture/depth_range", LGraphTextureDepthRange ); - - // Texture Blur ***************************************** - function LGraphTextureBlur() - { - this.addInput("Texture","Texture"); - this.addInput("Iterations","number"); - this.addInput("Intensity","number"); - this.addOutput("Blurred","Texture"); - this.properties = { intensity: 1, iterations: 1, preserve_aspect: false, scale:[1,1], precision: LGraphTexture.DEFAULT }; - } - - LGraphTextureBlur.title = "Blur"; - LGraphTextureBlur.desc = "Blur a texture"; - - LGraphTextureBlur.widgets_info = { - precision: { widget:"combo", values: LGraphTexture.MODE_VALUES } - }; - - LGraphTextureBlur.max_iterations = 20; - - LGraphTextureBlur.prototype.onExecute = function() - { - var tex = this.getInputData(0); - if(!tex) - return; - - if(!this.isOutputConnected(0)) - return; //saves work - - var temp = this._final_texture; - - if(!temp || temp.width != tex.width || temp.height != tex.height || temp.type != tex.type ) - { - //we need two textures to do the blurring - //this._temp_texture = new GL.Texture( tex.width, tex.height, { type: tex.type, format: gl.RGBA, filter: gl.LINEAR }); - temp = this._final_texture = new GL.Texture( tex.width, tex.height, { type: tex.type, format: gl.RGBA, filter: gl.LINEAR }); - } - - //iterations - var iterations = this.properties.iterations; - if( this.isInputConnected(1) ) - { - iterations = this.getInputData(1); - this.properties.iterations = iterations; - } - iterations = Math.min( Math.floor(iterations), LGraphTextureBlur.max_iterations ); - if(iterations == 0) //skip blurring - { - this.setOutputData(0, tex); - return; - } - - var intensity = this.properties.intensity; - if( this.isInputConnected(2) ) - { - intensity = this.getInputData(2); - this.properties.intensity = intensity; - } - - //blur sometimes needs an aspect correction - var aspect = LiteGraph.camera_aspect; - if(!aspect && window.gl !== undefined) - aspect = gl.canvas.height / gl.canvas.width; - if(!aspect) - aspect = 1; - aspect = this.properties.preserve_aspect ? aspect : 1; - - var scale = this.properties.scale || [1,1]; - tex.applyBlur( aspect * scale[0], scale[1], intensity, temp ); - for(var i = 1; i < iterations; ++i) - temp.applyBlur( aspect * scale[0] * (i+1), scale[1] * (i+1), intensity ); - - this.setOutputData(0, temp ); - } - - /* - LGraphTextureBlur.pixel_shader = "precision highp float;\n\ - precision highp float;\n\ - varying vec2 v_coord;\n\ - uniform sampler2D u_texture;\n\ - uniform vec2 u_offset;\n\ - uniform float u_intensity;\n\ - void main() {\n\ - vec4 sum = vec4(0.0);\n\ - vec4 center = texture2D(u_texture, v_coord);\n\ - sum += texture2D(u_texture, v_coord + u_offset * -4.0) * 0.05/0.98;\n\ - sum += texture2D(u_texture, v_coord + u_offset * -3.0) * 0.09/0.98;\n\ - sum += texture2D(u_texture, v_coord + u_offset * -2.0) * 0.12/0.98;\n\ - sum += texture2D(u_texture, v_coord + u_offset * -1.0) * 0.15/0.98;\n\ - sum += center * 0.16/0.98;\n\ - sum += texture2D(u_texture, v_coord + u_offset * 4.0) * 0.05/0.98;\n\ - sum += texture2D(u_texture, v_coord + u_offset * 3.0) * 0.09/0.98;\n\ - sum += texture2D(u_texture, v_coord + u_offset * 2.0) * 0.12/0.98;\n\ - sum += texture2D(u_texture, v_coord + u_offset * 1.0) * 0.15/0.98;\n\ - gl_FragColor = u_intensity * sum;\n\ - }\n\ - "; - */ - - LiteGraph.registerNodeType("texture/blur", LGraphTextureBlur ); - - - // Texture Glow ***************************************** - //based in https://catlikecoding.com/unity/tutorials/advanced-rendering/bloom/ - function LGraphTextureGlow() - { - this.addInput("in","Texture"); - this.addInput("dirt","Texture"); - this.addOutput("out","Texture"); - this.addOutput("glow","Texture"); - this.properties = { enabled: true, intensity: 1, persistence: 0.99, iterations:16, threshold:0, scale: 1, dirt_factor: 0.5, precision: LGraphTexture.DEFAULT }; - this._textures = []; - this._uniforms = { u_intensity: 1, u_texture: 0, u_glow_texture: 1, u_threshold: 0, u_texel_size: vec2.create() }; - } - - LGraphTextureGlow.title = "Glow"; - LGraphTextureGlow.desc = "Filters a texture giving it a glow effect"; - LGraphTextureGlow.weights = new Float32Array( [0.5,0.4,0.3,0.2] ); - - LGraphTextureGlow.widgets_info = { - "iterations": { type:"number", min: 0, max: 16, step: 1, precision: 0 }, - "threshold": { type:"number", min: 0, max: 10, step: 0.01, precision: 2 }, - "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } - }; - - LGraphTextureGlow.prototype.onGetInputs = function(){ - return [["enabled","boolean"],["threshold","number"],["intensity","number"],["persistence","number"],["iterations","number"],["dirt_factor","number"]]; - } - - LGraphTextureGlow.prototype.onGetOutputs = function(){ - return [["average","Texture"]]; - } - - LGraphTextureGlow.prototype.onExecute = function() - { - var tex = this.getInputData(0); - if(!tex) - return; - - if(!this.isAnyOutputConnected()) - return; //saves work - - if(this.properties.precision === LGraphTexture.PASS_THROUGH || this.getInputOrProperty("enabled" ) === false ) - { - this.setOutputData(0,tex); - return; - } - - var width = tex.width; - var height = tex.height; - - var texture_info = { format: tex.format, type: tex.type, minFilter: GL.LINEAR, magFilter: GL.LINEAR, wrap: gl.CLAMP_TO_EDGE }; - var type = LGraphTexture.getTextureType( this.properties.precision, tex ); - - var uniforms = this._uniforms; - var textures = this._textures; - - //cut - var shader = LGraphTextureGlow._cut_shader; - if(!shader) - shader = LGraphTextureGlow._cut_shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureGlow.cut_pixel_shader ); - - gl.disable( gl.DEPTH_TEST ); - gl.disable( gl.BLEND ); - - uniforms.u_threshold = this.getInputOrProperty("threshold"); - var currentDestination = textures[0] = GL.Texture.getTemporary( width, height, texture_info ); - tex.blit( currentDestination, shader.uniforms(uniforms) ); - var currentSource = currentDestination; - - var iterations = this.getInputOrProperty("iterations"); - iterations = Math.clamp( iterations, 1, 16) | 0; - var texel_size = uniforms.u_texel_size; - var intensity = this.getInputOrProperty("intensity"); - - uniforms.u_intensity = 1; - uniforms.u_delta = this.properties.scale; //1 - - //downscale/upscale shader - var shader = LGraphTextureGlow._shader; - if(!shader) - shader = LGraphTextureGlow._shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureGlow.scale_pixel_shader ); - - var i = 1; - //downscale - for (;i < iterations; i++) { - width = width>>1; - if( (height|0) > 1 ) - height = height>>1; - if( width < 2 ) - break; - currentDestination = textures[i] = GL.Texture.getTemporary( width, height, texture_info ); - texel_size[0] = 1 / currentSource.width; texel_size[1] = 1 / currentSource.height; - currentSource.blit( currentDestination, shader.uniforms(uniforms) ); - currentSource = currentDestination; - } - - //average - if(this.isOutputConnected(2)) - { - var average_texture = this._average_texture; - if(!average_texture || average_texture.type != tex.type || average_texture.format != tex.format ) - average_texture = this._average_texture = new GL.Texture( 1, 1, { type: tex.type, format: tex.format, filter: gl.LINEAR }); - texel_size[0] = 1 / currentSource.width; texel_size[1] = 1 / currentSource.height; - uniforms.u_intensity = intensity; - uniforms.u_delta = 1; - currentSource.blit( average_texture, shader.uniforms(uniforms) ); - this.setOutputData( 2, average_texture ); - } - - //upscale and blend - gl.enable( gl.BLEND ); - gl.blendFunc( gl.ONE, gl.ONE ); - uniforms.u_intensity = this.getInputOrProperty("persistence"); - uniforms.u_delta = 0.5; - - for (i -= 2; i >= 0; i--) // i-=2 => -1 to point to last element in array, -1 to go to texture above - { - currentDestination = textures[i]; - textures[i] = null; - texel_size[0] = 1 / currentSource.width; texel_size[1] = 1 / currentSource.height; - currentSource.blit( currentDestination, shader.uniforms(uniforms) ); - GL.Texture.releaseTemporary( currentSource ); - currentSource = currentDestination; - } - gl.disable( gl.BLEND ); - - //glow - if(this.isOutputConnected(1)) - { - var glow_texture = this._glow_texture; - if(!glow_texture || glow_texture.width != tex.width || glow_texture.height != tex.height || glow_texture.type != type || glow_texture.format != tex.format ) - glow_texture = this._glow_texture = new GL.Texture( tex.width, tex.height, { type: type, format: tex.format, filter: gl.LINEAR }); - currentSource.blit( glow_texture ); - this.setOutputData( 1, glow_texture); - } - - //final composition - if(this.isOutputConnected(0)) - { - var final_texture = this._final_texture; - if(!final_texture || final_texture.width != tex.width || final_texture.height != tex.height || final_texture.type != type || final_texture.format != tex.format ) - final_texture = this._final_texture = new GL.Texture( tex.width, tex.height, { type: type, format: tex.format, filter: gl.LINEAR }); - - var dirt_texture = this.getInputData(1); - var dirt_factor = this.getInputOrProperty("dirt_factor"); - - uniforms.u_intensity = intensity; - - shader = dirt_texture ? LGraphTextureGlow._dirt_final_shader : LGraphTextureGlow._final_shader; - if(!shader) - { - if(dirt_texture) - shader = LGraphTextureGlow._dirt_final_shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureGlow.final_pixel_shader, { USE_DIRT: "" } ); - else - shader = LGraphTextureGlow._final_shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphTextureGlow.final_pixel_shader ); - } - - final_texture.drawTo( function(){ - tex.bind(0); - currentSource.bind(1); - if(dirt_texture) - { - shader.setUniform( "u_dirt_factor", dirt_factor ); - shader.setUniform( "u_dirt_texture", dirt_texture.bind(2) ); - } - shader.toViewport( uniforms ); - }); - this.setOutputData( 0, final_texture ); - } - - GL.Texture.releaseTemporary( currentSource ); - } - - LGraphTextureGlow.cut_pixel_shader = "precision highp float;\n\ - varying vec2 v_coord;\n\ - uniform sampler2D u_texture;\n\ - uniform float u_threshold;\n\ - void main() {\n\ - gl_FragColor = max( texture2D( u_texture, v_coord ) - vec4( u_threshold ), vec4(0.0) );\n\ - }" - - LGraphTextureGlow.scale_pixel_shader = "precision highp float;\n\ - varying vec2 v_coord;\n\ - uniform sampler2D u_texture;\n\ - uniform vec2 u_texel_size;\n\ - uniform float u_delta;\n\ - uniform float u_intensity;\n\ - \n\ - vec4 sampleBox(vec2 uv) {\n\ - vec4 o = u_texel_size.xyxy * vec2(-u_delta, u_delta).xxyy;\n\ - vec4 s = texture2D( u_texture, uv + o.xy ) + texture2D( u_texture, uv + o.zy) + texture2D( u_texture, uv + o.xw) + texture2D( u_texture, uv + o.zw);\n\ - return s * 0.25;\n\ - }\n\ - void main() {\n\ - gl_FragColor = u_intensity * sampleBox( v_coord );\n\ - }" - - LGraphTextureGlow.final_pixel_shader = "precision highp float;\n\ - varying vec2 v_coord;\n\ - uniform sampler2D u_texture;\n\ - uniform sampler2D u_glow_texture;\n\ - #ifdef USE_DIRT\n\ - uniform sampler2D u_dirt_texture;\n\ - #endif\n\ - uniform vec2 u_texel_size;\n\ - uniform float u_delta;\n\ - uniform float u_intensity;\n\ - uniform float u_dirt_factor;\n\ - \n\ - vec4 sampleBox(vec2 uv) {\n\ - vec4 o = u_texel_size.xyxy * vec2(-u_delta, u_delta).xxyy;\n\ - vec4 s = texture2D( u_glow_texture, uv + o.xy ) + texture2D( u_glow_texture, uv + o.zy) + texture2D( u_glow_texture, uv + o.xw) + texture2D( u_glow_texture, uv + o.zw);\n\ - return s * 0.25;\n\ - }\n\ - void main() {\n\ - vec4 glow = sampleBox( v_coord );\n\ - #ifdef USE_DIRT\n\ - glow = mix( glow, glow * texture2D( u_dirt_texture, v_coord ), u_dirt_factor );\n\ - #endif\n\ - gl_FragColor = texture2D( u_texture, v_coord ) + u_intensity * glow;\n\ - }" - - LiteGraph.registerNodeType("texture/glow", LGraphTextureGlow ); - - - // Texture Blur ***************************************** - function LGraphTextureKuwaharaFilter() - { - this.addInput("Texture","Texture"); - this.addOutput("Filtered","Texture"); - this.properties = { intensity: 1, radius: 5 }; - } - - LGraphTextureKuwaharaFilter.title = "Kuwahara Filter"; - LGraphTextureKuwaharaFilter.desc = "Filters a texture giving an artistic oil canvas painting"; - - LGraphTextureKuwaharaFilter.max_radius = 10; - LGraphTextureKuwaharaFilter._shaders = []; - - LGraphTextureKuwaharaFilter.prototype.onExecute = function() - { - var tex = this.getInputData(0); - if(!tex) - return; - - if(!this.isOutputConnected(0)) - return; //saves work - - var temp = this._temp_texture; - - if(!temp || temp.width != tex.width || temp.height != tex.height || temp.type != tex.type ) - { - //we need two textures to do the blurring - this._temp_texture = new GL.Texture( tex.width, tex.height, { type: tex.type, format: gl.RGBA, filter: gl.LINEAR }); - //this._final_texture = new GL.Texture( tex.width, tex.height, { type: tex.type, format: gl.RGBA, filter: gl.LINEAR }); - } - - //iterations - var radius = this.properties.radius; - radius = Math.min( Math.floor(radius), LGraphTextureKuwaharaFilter.max_radius ); - if(radius == 0) //skip blurring - { - this.setOutputData(0, tex); - return; - } - - var intensity = this.properties.intensity; - - //blur sometimes needs an aspect correction - var aspect = LiteGraph.camera_aspect; - if(!aspect && window.gl !== undefined) - aspect = gl.canvas.height / gl.canvas.width; - if(!aspect) - aspect = 1; - aspect = this.properties.preserve_aspect ? aspect : 1; - - if(!LGraphTextureKuwaharaFilter._shaders[ radius ]) - LGraphTextureKuwaharaFilter._shaders[ radius ] = new GL.Shader( Shader.SCREEN_VERTEX_SHADER, LGraphTextureKuwaharaFilter.pixel_shader, { RADIUS: radius.toFixed(0) }); - - var shader = LGraphTextureKuwaharaFilter._shaders[ radius ]; - var mesh = GL.Mesh.getScreenQuad(); - tex.bind(0); - - this._temp_texture.drawTo( function() { - shader.uniforms({ u_texture: 0, u_intensity: intensity, u_resolution: [tex.width, tex.height], u_iResolution: [1/tex.width,1/tex.height]}).draw(mesh); - }); - - this.setOutputData(0, this._temp_texture); - } - -//from https://www.shadertoy.com/view/MsXSz4 -LGraphTextureKuwaharaFilter.pixel_shader = "\n\ - precision highp float;\n\ - varying vec2 v_coord;\n\ - uniform sampler2D u_texture;\n\ - uniform float u_intensity;\n\ - uniform vec2 u_resolution;\n\ - uniform vec2 u_iResolution;\n\ - #ifndef RADIUS\n\ - #define RADIUS 7\n\ - #endif\n\ - void main() {\n\ - \n\ - const int radius = RADIUS;\n\ - vec2 fragCoord = v_coord;\n\ - vec2 src_size = u_iResolution;\n\ - vec2 uv = v_coord;\n\ - float n = float((radius + 1) * (radius + 1));\n\ - int i;\n\ - int j;\n\ - vec3 m0 = vec3(0.0); vec3 m1 = vec3(0.0); vec3 m2 = vec3(0.0); vec3 m3 = vec3(0.0);\n\ - vec3 s0 = vec3(0.0); vec3 s1 = vec3(0.0); vec3 s2 = vec3(0.0); vec3 s3 = vec3(0.0);\n\ - vec3 c;\n\ - \n\ - for (int j = -radius; j <= 0; ++j) {\n\ - for (int i = -radius; i <= 0; ++i) {\n\ - c = texture2D(u_texture, uv + vec2(i,j) * src_size).rgb;\n\ - m0 += c;\n\ - s0 += c * c;\n\ - }\n\ - }\n\ - \n\ - for (int j = -radius; j <= 0; ++j) {\n\ - for (int i = 0; i <= radius; ++i) {\n\ - c = texture2D(u_texture, uv + vec2(i,j) * src_size).rgb;\n\ - m1 += c;\n\ - s1 += c * c;\n\ - }\n\ - }\n\ - \n\ - for (int j = 0; j <= radius; ++j) {\n\ - for (int i = 0; i <= radius; ++i) {\n\ - c = texture2D(u_texture, uv + vec2(i,j) * src_size).rgb;\n\ - m2 += c;\n\ - s2 += c * c;\n\ - }\n\ - }\n\ - \n\ - for (int j = 0; j <= radius; ++j) {\n\ - for (int i = -radius; i <= 0; ++i) {\n\ - c = texture2D(u_texture, uv + vec2(i,j) * src_size).rgb;\n\ - m3 += c;\n\ - s3 += c * c;\n\ - }\n\ - }\n\ - \n\ - float min_sigma2 = 1e+2;\n\ - m0 /= n;\n\ - s0 = abs(s0 / n - m0 * m0);\n\ - \n\ - float sigma2 = s0.r + s0.g + s0.b;\n\ - if (sigma2 < min_sigma2) {\n\ - min_sigma2 = sigma2;\n\ - gl_FragColor = vec4(m0, 1.0);\n\ - }\n\ - \n\ - m1 /= n;\n\ - s1 = abs(s1 / n - m1 * m1);\n\ - \n\ - sigma2 = s1.r + s1.g + s1.b;\n\ - if (sigma2 < min_sigma2) {\n\ - min_sigma2 = sigma2;\n\ - gl_FragColor = vec4(m1, 1.0);\n\ - }\n\ - \n\ - m2 /= n;\n\ - s2 = abs(s2 / n - m2 * m2);\n\ - \n\ - sigma2 = s2.r + s2.g + s2.b;\n\ - if (sigma2 < min_sigma2) {\n\ - min_sigma2 = sigma2;\n\ - gl_FragColor = vec4(m2, 1.0);\n\ - }\n\ - \n\ - m3 /= n;\n\ - s3 = abs(s3 / n - m3 * m3);\n\ - \n\ - sigma2 = s3.r + s3.g + s3.b;\n\ - if (sigma2 < min_sigma2) {\n\ - min_sigma2 = sigma2;\n\ - gl_FragColor = vec4(m3, 1.0);\n\ - }\n\ - }\n\ - "; - - LiteGraph.registerNodeType("texture/kuwahara", LGraphTextureKuwaharaFilter ); - - - // Texture Webcam ***************************************** - function LGraphTextureWebcam() - { - this.addOutput("Webcam","Texture"); - this.properties = { texture_name: "", facingMode: "user" }; - this.boxcolor = "black"; - this.version = 0; - } - - LGraphTextureWebcam.title = "Webcam"; - LGraphTextureWebcam.desc = "Webcam texture"; - - - LGraphTextureWebcam.prototype.openStream = function() - { - if (!navigator.getUserMedia) { - //console.log('getUserMedia() is not supported in your browser, use chrome and enable WebRTC from about://flags'); - return; - } - - this._waiting_confirmation = true; - - // Not showing vendor prefixes. - var constraints = { audio: false, video: { facingMode: this.properties.facingMode } }; - navigator.mediaDevices.getUserMedia( constraints ).then( this.streamReady.bind(this) ).catch( onFailSoHard ); - - var that = this; - function onFailSoHard(e) { - console.log('Webcam rejected', e); - that._webcam_stream = false; - that.boxcolor = "red"; - that.trigger("stream_error"); - }; - } - - LGraphTextureWebcam.prototype.closeStream = function() - { - if(this._webcam_stream) - { - var tracks = this._webcam_stream.getTracks(); - if(tracks.length) - { - for(var i = 0;i < tracks.length; ++i) - tracks[i].stop(); - } - this._webcam_stream = null; - this._video = null; - this.boxcolor = "black"; - this.trigger("stream_closed"); - } - } - - LGraphTextureWebcam.prototype.streamReady = function(localMediaStream) - { - this._webcam_stream = localMediaStream; - //this._waiting_confirmation = false; - this.boxcolor = "green"; - var video = this._video; - if(!video) - { - video = document.createElement("video"); - video.autoplay = true; - video.srcObject = localMediaStream; - this._video = video; - //document.body.appendChild( video ); //debug - //when video info is loaded (size and so) - video.onloadedmetadata = function(e) { - // Ready to go. Do some stuff. - console.log(e); - }; - } - this.trigger("stream_ready",video); - } - - LGraphTextureWebcam.prototype.onPropertyChanged = function(name,value) - { - if(name == "facingMode") - { - this.properties.facingMode = value; - this.closeStream(); - this.openStream(); - } - } - - LGraphTextureWebcam.prototype.onRemoved = function() - { - if(!this._webcam_stream) - return; - - var tracks = this._webcam_stream.getTracks(); - if(tracks.length) - { - for(var i = 0;i < tracks.length; ++i) - tracks[i].stop(); - } - - this._webcam_stream = null; - this._video = null; - } - - LGraphTextureWebcam.prototype.onDrawBackground = function(ctx) - { - if(this.flags.collapsed || this.size[1] <= 20) - return; - - if(!this._video) - return; - - //render to graph canvas - ctx.save(); - if(!ctx.webgl) //reverse image - ctx.drawImage(this._video, 0, 0, this.size[0], this.size[1]); - else - { - if(this._video_texture) - ctx.drawImage(this._video_texture, 0, 0, this.size[0], this.size[1]); - } - ctx.restore(); - } - - LGraphTextureWebcam.prototype.onExecute = function() - { - if(this._webcam_stream == null && !this._waiting_confirmation) - this.openStream(); - - if(!this._video || !this._video.videoWidth) - return; - - var width = this._video.videoWidth; - var height = this._video.videoHeight; - - var temp = this._video_texture; - if(!temp || temp.width != width || temp.height != height ) - this._video_texture = new GL.Texture( width, height, { format: gl.RGB, filter: gl.LINEAR }); - - this._video_texture.uploadImage( this._video ); - this._video_texture.version = ++this.version; - - if(this.properties.texture_name) - { - var container = LGraphTexture.getTexturesContainer(); - container[ this.properties.texture_name ] = this._video_texture; - } - - this.setOutputData(0,this._video_texture); - for(var i = 1; i < this.outputs.length; ++i) - { - if(!this.outputs[i]) - continue; - switch( this.outputs[i].name ) - { - case "width": this.setOutputData(i,this._video.videoWidth);break; - case "height": this.setOutputData(i,this._video.videoHeight);break; - } - } - } - - LGraphTextureWebcam.prototype.onGetOutputs = function() - { - return [["width","number"],["height","number"],["stream_ready",LiteGraph.EVENT],["stream_closed",LiteGraph.EVENT],["stream_error",LiteGraph.EVENT]]; - } - - LiteGraph.registerNodeType("texture/webcam", LGraphTextureWebcam ); - - - - //from https://github.com/spite/Wagner - function LGraphLensFX() - { - this.addInput("in","Texture"); - this.addInput("f","number"); - this.addOutput("out","Texture"); - this.properties = { enabled: true, factor: 1, precision: LGraphTexture.LOW }; - - this._uniforms = { u_texture: 0, u_factor: 1 }; - } - - LGraphLensFX.title = "Lens FX"; - LGraphLensFX.desc = "distortion and chromatic aberration"; - - LGraphLensFX.widgets_info = { - "precision": { widget:"combo", values: LGraphTexture.MODE_VALUES } - }; - - LGraphLensFX.prototype.onGetInputs = function() { return [["enabled","boolean"]]; } - - LGraphLensFX.prototype.onExecute = function() - { - var tex = this.getInputData(0); - if(!tex) - return; - - if(!this.isOutputConnected(0)) - return; //saves work - - if(this.properties.precision === LGraphTexture.PASS_THROUGH || this.getInputOrProperty("enabled" ) === false ) - { - this.setOutputData(0, tex ); - return; - } - - var temp = this._temp_texture; - if(!temp || temp.width != tex.width || temp.height != tex.height || temp.type != tex.type ) - temp = this._temp_texture = new GL.Texture( tex.width, tex.height, { type: tex.type, format: gl.RGBA, filter: gl.LINEAR }); - - var shader = LGraphLensFX._shader; - if(!shader) - shader = LGraphLensFX._shader = new GL.Shader( GL.Shader.SCREEN_VERTEX_SHADER, LGraphLensFX.pixel_shader ); - - var factor = this.getInputData(1); - if(factor == null) - factor = this.properties.factor; - - var uniforms = this._uniforms; - uniforms.u_factor = factor; - - //apply shader - gl.disable( gl.DEPTH_TEST ); - temp.drawTo(function(){ - tex.bind(0); - shader.uniforms(uniforms).draw( GL.Mesh.getScreenQuad() ); - }); - - this.setOutputData(0,temp); - } - - LGraphLensFX.pixel_shader = "precision highp float;\n\ - varying vec2 v_coord;\n\ - uniform sampler2D u_texture;\n\ - uniform float u_factor;\n\ - vec2 barrelDistortion(vec2 coord, float amt) {\n\ - vec2 cc = coord - 0.5;\n\ - float dist = dot(cc, cc);\n\ - return coord + cc * dist * amt;\n\ - }\n\ - \n\ - float sat( float t )\n\ - {\n\ - return clamp( t, 0.0, 1.0 );\n\ - }\n\ - \n\ - float linterp( float t ) {\n\ - return sat( 1.0 - abs( 2.0*t - 1.0 ) );\n\ - }\n\ - \n\ - float remap( float t, float a, float b ) {\n\ - return sat( (t - a) / (b - a) );\n\ - }\n\ - \n\ - vec4 spectrum_offset( float t ) {\n\ - vec4 ret;\n\ - float lo = step(t,0.5);\n\ - float hi = 1.0-lo;\n\ - float w = linterp( remap( t, 1.0/6.0, 5.0/6.0 ) );\n\ - ret = vec4(lo,1.0,hi, 1.) * vec4(1.0-w, w, 1.0-w, 1.);\n\ - \n\ - return pow( ret, vec4(1.0/2.2) );\n\ - }\n\ - \n\ - const float max_distort = 2.2;\n\ - const int num_iter = 12;\n\ - const float reci_num_iter_f = 1.0 / float(num_iter);\n\ - \n\ - void main()\n\ - { \n\ - vec2 uv=v_coord;\n\ - vec4 sumcol = vec4(0.0);\n\ - vec4 sumw = vec4(0.0); \n\ - for ( int i=0; ipixelcode must be vec3
\t\t\tuvcode must be vec2, is optional
\t\t\tuv: tex. coords
color: texture
colorB: textureB
time: scene time
value: input value
"; -this.properties={value:1,uvcode:"",pixelcode:"color + colorB * value",precision:e.DEFAULT}};s.widgets_info={uvcode:{widget:"textarea",height:100},pixelcode:{widget:"textarea",height:100},precision:{widget:"combo",values:e.MODE_VALUES}};s.title="Operation";s.desc="Texture shader operation";s.prototype.getExtraMenuOptions=function(a){var b=this;return[{content:b.properties.show?"Hide Texture":"Show Texture",callback:function(){b.properties.show=!b.properties.show}}]};s.prototype.onDrawBackground=function(a){this.flags.collapsed|| -20>=this.size[1]||!this.properties.show||!this._tex||this._tex.gl!=a||(a.save(),a.drawImage(this._tex,0,0,this.size[0],this.size[1]),a.restore())};s.prototype.onExecute=function(){var a=this.getInputData(0);if(this.isOutputConnected(0))if(this.properties.precision===e.PASS_THROUGH)this.setOutputData(0,a);else{var b=this.getInputData(1);if(this.properties.uvcode||this.properties.pixelcode){var c=512,d=512;a?(c=a.width,d=a.height):b&&(c=b.width,d=b.height);var f=e.getTextureType(this.properties.precision, -a);this._tex=a||this._tex?e.getTargetTexture(a||this._tex,this._tex,this.properties.precision):new GL.Texture(c,d,{type:f,format:gl.RGBA,filter:gl.LINEAR});f="";this.properties.uvcode&&(f="uv = "+this.properties.uvcode,-1!=this.properties.uvcode.indexOf(";")&&(f=this.properties.uvcode));var g="";this.properties.pixelcode&&(g="result = "+this.properties.pixelcode,-1!=this.properties.pixelcode.indexOf(";")&&(g=this.properties.pixelcode));var l=this._shader;if(!l||this._shader_code!=f+"|"+g){try{this._shader= -new GL.Shader(Shader.SCREEN_VERTEX_SHADER,s.pixel_shader,{UV_CODE:f,PIXEL_CODE:g}),this.boxcolor="#00FF00"}catch(h){console.log("Error compiling shader: ",h);this.boxcolor="#FF0000";return}this.boxcolor="#FF0000";this._shader_code=f+"|"+g;l=this._shader}if(l){this.boxcolor="green";var k=this.getInputData(2);null!=k?this.properties.value=k:k=parseFloat(this.properties.value);var p=this.graph.getTime();this._tex.drawTo(function(){gl.disable(gl.DEPTH_TEST);gl.disable(gl.CULL_FACE);gl.disable(gl.BLEND); -a&&a.bind(0);b&&b.bind(1);var f=Mesh.getScreenQuad();l.uniforms({u_texture:0,u_textureB:1,value:k,texSize:[c,d],time:p}).draw(f)});this.setOutputData(0,this._tex)}else this.boxcolor="red"}}};s.pixel_shader="precision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_texture;\n\t\t\tuniform sampler2D u_textureB;\n\t\t\tvarying vec2 v_coord;\n\t\t\tuniform vec2 texSize;\n\t\t\tuniform float time;\n\t\t\tuniform float value;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tvec2 uv = v_coord;\n\t\t\t\tUV_CODE;\n\t\t\t\tvec4 color4 = texture2D(u_texture, uv);\n\t\t\t\tvec3 color = color4.rgb;\n\t\t\t\tvec4 color4B = texture2D(u_textureB, uv);\n\t\t\t\tvec3 colorB = color4B.rgb;\n\t\t\t\tvec3 result = color;\n\t\t\t\tfloat alpha = 1.0;\n\t\t\t\tPIXEL_CODE;\n\t\t\t\tgl_FragColor = vec4(result, alpha);\n\t\t\t}\n\t\t\t"; -h.registerNodeType("texture/operation",s);var r=function(){this.addOutput("out","Texture");this.properties={code:"",width:512,height:512,precision:e.DEFAULT};this.properties.code="\nvoid main() {\n vec2 uv = v_coord;\n vec3 color = vec3(0.0);\n//your code here\n\ngl_FragColor = vec4(color, 1.0);\n}\n";this._uniforms={in_texture:0,texSize:vec2.create(),time:0}};r.title="Shader";r.desc="Texture shader";r.widgets_info={code:{type:"code"},precision:{widget:"combo",values:e.MODE_VALUES}};r.prototype.onPropertyChanged= -function(a,b){if("code"==a){var c=this.getShader();if(c){var d=c.uniformInfo;if(this.inputs)for(var f={},g=0;g=h.NOTEON||b<=h.NOTEOFF)this.channel=a&15};Object.defineProperty(h.prototype,"velocity",{get:function(){return this.cmd==h.NOTEON?this.data[2]:-1},set:function(a){this.data[2]=a},enumerable:!0});h.notes="A A# B C C# D D# E F F# G G#".split(" ");h.note_to_index={A:0,"A#":1,B:2,C:3,"C#":4,D:5,"D#":6,E:7,F:8,"F#":9,G:10,"G#":11};Object.defineProperty(h.prototype, -"note",{get:function(){return this.cmd!=h.NOTEON?-1:h.toNoteString(this.data[1],!0)},set:function(a){throw"notes cannot be assigned this way, must modify the data[1]";},enumerable:!0});Object.defineProperty(h.prototype,"octave",{get:function(){return this.cmd!=h.NOTEON?-1:Math.floor((this.data[1]-24)/12+1)},set:function(a){throw"octave cannot be assigned this way, must modify the data[1]";},enumerable:!0});h.prototype.getPitch=function(){return 440*Math.pow(2,(this.data[1]-69)/12)};h.computePitch= -function(a){return 440*Math.pow(2,(a-69)/12)};h.prototype.getCC=function(){return this.data[1]};h.prototype.getCCValue=function(){return this.data[2]};h.prototype.getPitchBend=function(){return this.data[1]+(this.data[2]<<7)-8192};h.computePitchBend=function(a,b){return a+(b<<7)-8192};h.prototype.setCommandFromString=function(a){this.cmd=h.computeCommandFromString(a)};h.computeCommandFromString=function(a){if(!a)return 0;if(a&&a.constructor===Number)return a;a=a.toUpperCase();switch(a){case "NOTE ON":case "NOTEON":return h.NOTEON; -case "NOTE OFF":case "NOTEOFF":return h.NOTEON;case "KEY PRESSURE":case "KEYPRESSURE":return h.KEYPRESSURE;case "CONTROLLER CHANGE":case "CONTROLLERCHANGE":case "CC":return h.CONTROLLERCHANGE;case "PROGRAM CHANGE":case "PROGRAMCHANGE":case "PC":return h.PROGRAMCHANGE;case "CHANNEL PRESSURE":case "CHANNELPRESSURE":return h.CHANNELPRESSURE;case "PITCH BEND":case "PITCHBEND":return h.PITCHBEND;case "TIME TICK":case "TIMETICK":return h.TIMETICK;default:return Number(a)}};h.toNoteString=function(a,b){a= -Math.round(a);var d,e=Math.floor((a-24)/12+1);d=(a-21)%12;0>d&&(d=12+d);return h.notes[d]+(b?"":e)};h.NoteStringToPitch=function(a){a=a.toUpperCase();var b=a[0],d=4;"#"==a[1]?(b+="#",2this.properties.max_value||this.trigger("on_midi",b)};b.registerNodeType("midi/filter",r);t.title="MIDIEvent";t.desc="Create a MIDI Event";t.color="#243";t.prototype.onAction= -function(a,b){"assign"==a?(this.properties.channel=b.channel,this.properties.cmd=b.cmd,this.properties.value1=b.data[1],this.properties.value2=b.data[2]):(b=this.midi_event,b.channel=this.properties.channel,this.properties.cmd&&this.properties.cmd.constructor===String?b.setCommandFromString(this.properties.cmd):b.cmd=this.properties.cmd,b.data[0]=b.cmd|b.channel,b.data[1]=Number(this.properties.value1),b.data[2]=Number(this.properties.value2),this.trigger("on_midi",b))};t.prototype.onExecute=function(){var a= -this.properties;if(this.inputs)for(var b=0;b a;++a)this.valid_notes[a]=-1!=this.notes_pitches.indexOf(a);for(a=0;12>a;++a)if(this.valid_notes[a])this.offset_notes[a]=0;else for(var b=1;12>b;++b){if(this.valid_notes[(a-b)%12]){this.offset_notes[a]=-b;break}if(this.valid_notes[(a+ -b)%12]){this.offset_notes[a]=b;break}}};n.prototype.onAction=function(a,b){b&&b.constructor===h&&(b.data[0]==h.NOTEON||b.data[0]==h.NOTEOFF?(this.midi_event=new h,this.midi_event.setup(b.data),this.midi_event.data[1]+=this.offset_notes[h.note_to_index[b.note]],this.trigger("out",this.midi_event)):this.trigger("out",b))};n.prototype.onExecute=function(){var a=this.getInputData(1);null!=a&&a!=this._current_scale&&this.processScale(a)};b.registerNodeType("midi/quantize",n);m.title="MIDI Play";m.desc= -"Plays a MIDI note";m.color="#243";m.prototype.onAction=function(a,b){if(b&&b.constructor===h){if(this.instrument&&b.data[0]==h.NOTEON){var d=b.note;if(!d||"undefined"==d||d.constructor!==String)return;this.instrument.play(d,b.octave,this.properties.duration,this.properties.volume)}this.trigger("note",b)}};m.prototype.onExecute=function(){var a=this.getInputData(1);null!=a&&(this.properties.volume=a);a=this.getInputData(2);null!=a&&(this.properties.duration=a)};b.registerNodeType("midi/play",m);a.title= -"MIDI Keys";a.desc="Keyboard to play notes";a.color="#243";a.keys=[{x:0,w:1,h:1,t:0},{x:0.75,w:0.5,h:0.6,t:1},{x:1,w:1,h:1,t:0},{x:1.75,w:0.5,h:0.6,t:1},{x:2,w:1,h:1,t:0},{x:2.75,w:0.5,h:0.6,t:1},{x:3,w:1,h:1,t:0},{x:4,w:1,h:1,t:0},{x:4.75,w:0.5,h:0.6,t:1},{x:5,w:1,h:1,t:0},{x:5.75,w:0.5,h:0.6,t:1},{x:6,w:1,h:1,t:0}];a.prototype.onDrawBackground=function(b){if(!this.flags.collapsed){var d=12*this.properties.num_octaves;this.keys.length=d;for(var e=this.size[0]/(7*this.properties.num_octaves),l=this.size[1], -h=0;2>h;h++)for(var k=0;k m+n||b[1]>k))return h}}return-1};a.prototype.onAction= -function(a,b){if("reset"==a)for(var d=0;d b[1])){var d=this.getKeyIndex(b);this.keys[d]=!0;this._last_key=d;var d=12*(this.properties.start_octave-1)+29+d,e=new h;e.setup([h.NOTEON,d,100]);this.trigger("note", -e);return!0}};a.prototype.onMouseMove=function(a,b){if(!(0>b[1]||-1==this._last_key)){this.setDirtyCanvas(!0);var d=this.getKeyIndex(b);if(this._last_key==d)return!0;this.keys[this._last_key]=!1;var e=12*(this.properties.start_octave-1)+29+this._last_key,k=new h;k.setup([h.NOTEOFF,e,100]);this.trigger("note",k);this.keys[d]=!0;e=12*(this.properties.start_octave-1)+29+d;k=new h;k.setup([h.NOTEON,e,100]);this.trigger("note",k);this._last_key=d;return!0}};a.prototype.onMouseUp=function(a,b){if(!(0>b[1])){var d= -this.getKeyIndex(b);this.keys[d]=!1;this._last_key=-1;var d=12*(this.properties.start_octave-1)+29+d,e=new h;e.setup([h.NOTEOFF,d,100]);this.trigger("note",e);return!0}};b.registerNodeType("midi/keys",a)})(this); -(function(v){function h(){this.properties={src:"",gain:0.5,loop:!0,autoplay:!0,playbackRate:1};this._loading_audio=!1;this._audiobuffer=null;this._audionodes=[];this._last_sourcenode=null;this.addOutput("out","audio");this.addInput("gain","number");this.audionode=g.getAudioContext().createGain();this.audionode.graphnode=this;this.audionode.gain.value=this.properties.gain;this.properties.src&&this.loadSound(this.properties.src)}function e(){this.properties={gain:0.5};this._audionodes=[];this._media_stream= -null;this.addOutput("out","audio");this.addInput("gain","number");this.audionode=g.getAudioContext().createGain();this.audionode.graphnode=this;this.audionode.gain.value=this.properties.gain}function q(){this.properties={fftSize:2048,minDecibels:-100,maxDecibels:-10,smoothingTimeConstant:0.5};this.audionode=g.getAudioContext().createAnalyser();this.audionode.graphnode=this;this.audionode.fftSize=this.properties.fftSize;this.audionode.minDecibels=this.properties.minDecibels;this.audionode.maxDecibels= -this.properties.maxDecibels;this.audionode.smoothingTimeConstant=this.properties.smoothingTimeConstant;this.addInput("in","audio");this.addOutput("freqs","array");this.addOutput("samples","array");this._time_bin=this._freq_bin=null}function d(){this.properties={gain:1};this.audionode=g.getAudioContext().createGain();this.addInput("in","audio");this.addInput("gain","number");this.addOutput("out","audio")}function s(){this.properties={impulse_src:"",normalize:!0};this.audionode=g.getAudioContext().createConvolver(); -this.addInput("in","audio");this.addOutput("out","audio")}function r(){this.properties={threshold:-50,knee:40,ratio:12,reduction:-20,attack:0,release:0.25};this.audionode=g.getAudioContext().createDynamicsCompressor();this.addInput("in","audio");this.addOutput("out","audio")}function t(){this.properties={};this.audionode=g.getAudioContext().createWaveShaper();this.addInput("in","audio");this.addInput("shape","waveshape");this.addOutput("out","audio")}function x(){this.properties={gain1:0.5,gain2:0.5}; -this.audionode=g.getAudioContext().createGain();this.audionode1=g.getAudioContext().createGain();this.audionode1.gain.value=this.properties.gain1;this.audionode2=g.getAudioContext().createGain();this.audionode2.gain.value=this.properties.gain2;this.audionode1.connect(this.audionode);this.audionode2.connect(this.audionode);this.addInput("in1","audio");this.addInput("in1 gain","number");this.addInput("in2","audio");this.addInput("in2 gain","number");this.addOutput("out","audio")}function k(){this.properties= -{delayTime:0.5};this.audionode=g.getAudioContext().createDelay(10);this.audionode.delayTime.value=this.properties.delayTime;this.addInput("in","audio");this.addInput("time","number");this.addOutput("out","audio")}function u(){this.properties={frequency:350,detune:0,Q:1};this.addProperty("type","lowpass","enum",{values:"lowpass highpass bandpass lowshelf highshelf peaking notch allpass".split(" ")});this.audionode=g.getAudioContext().createBiquadFilter();this.addInput("in","audio");this.addOutput("out", -"audio")}function n(){this.properties={frequency:440,detune:0,type:"sine"};this.addProperty("type","sine","enum",{values:["sine","square","sawtooth","triangle","custom"]});this.audionode=g.getAudioContext().createOscillator();this.addOutput("out","audio")}function m(){this.properties={continuous:!0,mark:-1};this.addInput("data","array");this.addInput("mark","number");this.size=[300,200];this._last_buffer=null}function a(){this.properties={band:440,amplitude:1};this.addInput("freqs","array");this.addOutput("signal", -"number")}function b(){if(!b.default_code){var a=b.default_function.toString(),c=a.indexOf("{")+1,d=a.lastIndexOf("}");b.default_code=a.substr(c,d-c)}this.properties={code:b.default_code};a=g.getAudioContext();a.createScriptProcessor?this.audionode=a.createScriptProcessor(4096,1,1):(console.warn("ScriptProcessorNode deprecated"),this.audionode=a.createGain());this.processCode();b._bypass_function||(b._bypass_function=this.audionode.onaudioprocess);this.addInput("in","audio");this.addOutput("out", -"audio")}function c(){this.audionode=g.getAudioContext().destination;this.addInput("in","audio")}var f=v.LiteGraph,g={};v.LGAudio=g;g.getAudioContext=function(){if(!this._audio_context){window.AudioContext=window.AudioContext||window.webkitAudioContext;if(!window.AudioContext)return console.error("AudioContext not supported by browser"),null;this._audio_context=new AudioContext;this._audio_context.onmessage=function(a){console.log("msg",a)};this._audio_context.onended=function(a){console.log("ended", -a)};this._audio_context.oncomplete=function(a){console.log("complete",a)}}return this._audio_context};g.connect=function(a,b){try{a.connect(b)}catch(c){console.warn("LGraphAudio:",c)}};g.disconnect=function(a,b){try{a.disconnect(b)}catch(c){console.warn("LGraphAudio:",c)}};g.changeAllAudiosConnections=function(a,b){if(a.inputs)for(var c=0;c =this.size[0]&&(e=this.size[0]-1),a.strokeStyle="red",a.beginPath(),a.moveTo(e,d),a.lineTo(e,0),a.stroke())}};m.title="Visualization";m.desc="Audio Visualization";f.registerNodeType("audio/visualization",m);a.prototype.onExecute=function(){if(this._freqs=this.getInputData(0)){var a=this.properties.band,b=this.getInputData(1);void 0!==b&&(a=b);b=g.getAudioContext().sampleRate/this._freqs.length; -b=a/b*2;b>=this._freqs.length?b=this._freqs[this._freqs.length-1]:(a=b|0,b-=a,b=this._freqs[a]*(1-b)+this._freqs[a+1]*b);this.setOutputData(0,b/255*this.properties.amplitude)}};a.prototype.onGetInputs=function(){return[["band","number"]]};a.title="Signal";a.desc="extract the signal of some frequency";f.registerNodeType("audio/signal",a);b.prototype.onAdded=function(a){a.status==LGraph.STATUS_RUNNING&&(this.audionode.onaudioprocess=this._callback)};b["@code"]={widget:"code"};b.prototype.onStart=function(){this.audionode.onaudioprocess= -this._callback};b.prototype.onStop=function(){this.audionode.onaudioprocess=b._bypass_function};b.prototype.onPause=function(){this.audionode.onaudioprocess=b._bypass_function};b.prototype.onUnpause=function(){this.audionode.onaudioprocess=this._callback};b.prototype.onExecute=function(){};b.prototype.onRemoved=function(){this.audionode.onaudioprocess=b._bypass_function};b.prototype.processCode=function(){try{this._script=new new Function("properties",this.properties.code)(this.properties),this._old_code= -this.properties.code,this._callback=this._script.onaudioprocess}catch(a){console.error("Error in onaudioprocess code",a),this._callback=b._bypass_function,this.audionode.onaudioprocess=this._callback}};b.prototype.onPropertyChanged=function(a,b){"code"==a&&(this.properties.code=b,this.processCode(),this.graph&&this.graph.status==LGraph.STATUS_RUNNING&&(this.audionode.onaudioprocess=this._callback))};b.default_function=function(){this.onaudioprocess=function(a){var b=a.inputBuffer;a=a.outputBuffer; -for(var c=0;c m && (m = Math.max(0, h + m)); + if (null == q || q > h) { + q = h; + } + q = Number(q); + 0 > q && (q = Math.max(0, h + q)); + for (m = Number(m || 0); m < q; m++) { + this[m] = d; + } + return this; + }; +}, "es6", "es3"); +$jscomp.SYMBOL_PREFIX = "jscomp_symbol_"; +$jscomp.initSymbol = function() { + $jscomp.initSymbol = function() { + }; + $jscomp.global.Symbol || ($jscomp.global.Symbol = $jscomp.Symbol); +}; +$jscomp.Symbol = function() { + var v = 0; + return function(d) { + return $jscomp.SYMBOL_PREFIX + (d || "") + v++; + }; +}(); +$jscomp.initSymbolIterator = function() { + $jscomp.initSymbol(); + var v = $jscomp.global.Symbol.iterator; + v || (v = $jscomp.global.Symbol.iterator = $jscomp.global.Symbol("iterator")); + "function" != typeof Array.prototype[v] && $jscomp.defineProperty(Array.prototype, v, {configurable:!0, writable:!0, value:function() { + return $jscomp.arrayIterator(this); + }}); + $jscomp.initSymbolIterator = function() { + }; +}; +$jscomp.arrayIterator = function(v) { + var d = 0; + return $jscomp.iteratorPrototype(function() { + return d < v.length ? {done:!1, value:v[d++]} : {done:!0}; + }); +}; +$jscomp.iteratorPrototype = function(v) { + $jscomp.initSymbolIterator(); + v = {next:v}; + v[$jscomp.global.Symbol.iterator] = function() { + return this; + }; + return v; +}; +$jscomp.iteratorFromArray = function(v, d) { + $jscomp.initSymbolIterator(); + v instanceof String && (v += ""); + var m = 0, q = {next:function() { + if (m < v.length) { + var h = m++; + return {value:d(h, v[h]), done:!1}; + } + q.next = function() { + return {done:!0, value:void 0}; + }; + return q.next(); + }}; + q[Symbol.iterator] = function() { + return q; + }; + return q; +}; +$jscomp.polyfill("Array.prototype.values", function(v) { + return v ? v : function() { + return $jscomp.iteratorFromArray(this, function(d, m) { + return m; + }); + }; +}, "es8", "es3"); +$jscomp.polyfill("Array.prototype.keys", function(v) { + return v ? v : function() { + return $jscomp.iteratorFromArray(this, function(d) { + return d; + }); + }; +}, "es6", "es3"); +(function(v) { + function d(a) { + l.debug && console.log("Graph created"); + this.list_of_graphcanvas = null; + this.clear(); + a && this.configure(a); + } + function m(a) { + this._ctor(a); + } + function q(a) { + this._ctor(a); + } + function h(a, b, c) { + c = c || {}; + this.background_image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII="; + a && a.constructor === String && (a = document.querySelector(a)); + this.max_zoom = 10; + this.min_zoom = 0.1; + this.zoom_modify_alpha = !0; + this.title_text_font = "bold " + l.NODE_TEXT_SIZE + "px Arial"; + this.inner_text_font = "normal " + l.NODE_SUBTEXT_SIZE + "px Arial"; + this.node_title_color = l.NODE_TITLE_COLOR; + this.default_link_color = l.LINK_COLOR; + this.default_connection_color = {input_off:"#AAB", input_on:"#7F7", output_off:"#AAB", output_on:"#7F7"}; + this.highquality_render = !0; + this.use_gradients = !1; + this.editor_alpha = 1; + this.pause_rendering = !1; + this.render_only_selected = this.clear_background = this.render_shadows = !0; + this.live_mode = !1; + this.allow_searchbox = this.allow_interaction = this.allow_dragnodes = this.allow_dragcanvas = this.show_info = !0; + this.drag_mode = this.allow_reconnect_links = !1; + this.filter = this.dragging_rectangle = null; + this.always_render_background = !1; + this.render_canvas_border = !0; + this.render_connections_shadows = !1; + this.render_connection_arrows = this.render_curved_connections = this.render_connections_border = !0; + this.render_execution_order = !1; + this.canvas_mouse = [0, 0]; + this.onDrawOverlay = this.onDrawForeground = this.onDrawBackground = this.onMouse = this.onSearchBoxSelection = this.onSearchBox = null; + this.connections_width = 3; + this.round_radius = 8; + this.node_widget = this.current_node = null; + this.last_mouse_position = [0, 0]; + this.visible_area = new Float32Array(4); + b && b.attachCanvas(this); + this.setCanvas(a); + this.clear(); + c.skip_render || this.startRendering(); + this.autoresize = c.autoresize; + } + function u(a, b) { + return Math.sqrt((b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1])); + } + function t(a, b, c, e, f, k) { + return c < a && c + f > a && e < b && e + k > b ? !0 : !1; + } + function w(a, b) { + var c = a[0] + a[2], e = a[1] + a[3], f = b[1] + b[3]; + return a[0] > b[0] + b[2] || a[1] > f || c < b[0] || e < b[1] ? !1 : !0; + } + function y(a, b) { + function c(a) { + var c = parseInt(f.style.top); + f.style.top = (c + a.deltaY * b.scroll_speed).toFixed() + "px"; + a.preventDefault(); + return !0; + } + this.options = b = b || {}; + var e = this; + b.parentMenu && (b.parentMenu.constructor !== this.constructor ? (console.error("parentMenu must be of class ContextMenu, ignoring it"), b.parentMenu = null) : (this.parentMenu = b.parentMenu, this.parentMenu.lock = !0, this.parentMenu.current_submenu = this)); + b.event && b.event.constructor !== MouseEvent && b.event.constructor !== CustomEvent && (console.error("Event passed to ContextMenu is not of type MouseEvent or CustomEvent. Ignoring it."), b.event = null); + var f = document.createElement("div"); + f.className = "litegraph litecontextmenu litemenubar-panel"; + b.className && (f.className += " " + b.className); + f.style.minWidth = 100; + f.style.minHeight = 100; + f.style.pointerEvents = "none"; + setTimeout(function() { + f.style.pointerEvents = "auto"; + }, 100); + f.addEventListener("mouseup", function(a) { + a.preventDefault(); + return !0; + }, !0); + f.addEventListener("contextmenu", function(a) { + if (2 != a.button) { + return !1; + } + a.preventDefault(); + return !1; + }, !0); + f.addEventListener("mousedown", function(a) { + if (2 == a.button) { + return e.close(), a.preventDefault(), !0; + } + }, !0); + b.scroll_speed || (b.scroll_speed = 0.1); + f.addEventListener("wheel", c, !0); + f.addEventListener("mousewheel", c, !0); + this.root = f; + if (b.title) { + var k = document.createElement("div"); + k.className = "litemenu-title"; + k.innerHTML = b.title; + f.appendChild(k); + } + k = 0; + for (var n in a) { + var l = a.constructor == Array ? a[n] : n; + null != l && l.constructor !== String && (l = void 0 === l.content ? String(l) : l.content); + this.addItem(l, a[n], b); + k++; + } + f.addEventListener("mouseleave", function(a) { + e.lock || (f.closing_timer && clearTimeout(f.closing_timer), f.closing_timer = setTimeout(e.close.bind(e, a), 500)); + }); + f.addEventListener("mouseenter", function(a) { + f.closing_timer && clearTimeout(f.closing_timer); + }); + a = document; + b.event && (a = b.event.target.ownerDocument); + a || (a = document); + a.body.appendChild(f); + n = b.left || 0; + a = b.top || 0; + b.event && (n = b.event.pageX - 10, a = b.event.pageY - 10, b.title && (a -= 20), b.parentMenu && (n = b.parentMenu.root.getBoundingClientRect(), n = n.left + n.width), k = document.body.getBoundingClientRect(), l = f.getBoundingClientRect(), n > k.width - l.width - 10 && (n = k.width - l.width - 10), a > k.height - l.height - 10 && (a = k.height - l.height - 10)); + f.style.left = n + "px"; + f.style.top = a + "px"; + } + var l = v.LiteGraph = {CANVAS_GRID_SIZE:10, NODE_TITLE_HEIGHT:20, NODE_SLOT_HEIGHT:15, NODE_WIDGET_HEIGHT:20, NODE_WIDTH:140, NODE_MIN_WIDTH:50, NODE_COLLAPSED_RADIUS:10, NODE_COLLAPSED_WIDTH:80, NODE_TITLE_COLOR:"#999", NODE_TEXT_SIZE:14, NODE_TEXT_COLOR:"#AAA", NODE_SUBTEXT_SIZE:12, NODE_DEFAULT_COLOR:"#333", NODE_DEFAULT_BGCOLOR:"#444", NODE_DEFAULT_BOXCOLOR:"#666", NODE_DEFAULT_SHAPE:"box", DEFAULT_SHADOW_COLOR:"rgba(0,0,0,0.5)", DEFAULT_GROUP_FONT:24, LINK_COLOR:"#AAD", EVENT_LINK_COLOR:"#F85", + CONNECTING_LINK_COLOR:"#AFA", MAX_NUMBER_OF_NODES:1000, DEFAULT_POSITION:[100, 100], VALID_SHAPES:["default", "box", "round", "card"], BOX_SHAPE:1, ROUND_SHAPE:2, CIRCLE_SHAPE:3, CARD_SHAPE:4, ARROW_SHAPE:5, INPUT:1, OUTPUT:2, EVENT:-1, ACTION:-1, ALWAYS:0, ON_EVENT:1, NEVER:2, ON_TRIGGER:3, UP:1, DOWN:2, LEFT:3, RIGHT:4, CENTER:5, NORMAL_TITLE:0, NO_TITLE:1, TRANSPARENT_TITLE:2, AUTOHIDE_TITLE:3, proxy:null, node_images_path:"", debug:!1, throw_errors:!0, allow_scripts:!1, registered_node_types:{}, + node_types_by_file_extension:{}, Nodes:{}, searchbox_extras:{}, registerNodeType:function(a, b) { + if (!b.prototype) { + throw "Cannot register a simple object, it must be a class with a prototype"; + } + b.type = a; + l.debug && console.log("Node registered: " + a); + a.split("/"); + var c = b.name, e = a.lastIndexOf("/"); + b.category = a.substr(0, e); + b.title || (b.title = c); + if (b.prototype) { + for (var f in m.prototype) { + b.prototype[f] || (b.prototype[f] = m.prototype[f]); + } + } + Object.defineProperty(b.prototype, "shape", {set:function(a) { + switch(a) { + case "default": + delete this._shape; + break; + case "box": + this._shape = l.BOX_SHAPE; + break; + case "round": + this._shape = l.ROUND_SHAPE; + break; + case "circle": + this._shape = l.CIRCLE_SHAPE; + break; + case "card": + this._shape = l.CARD_SHAPE; + break; + default: + this._shape = a; + } + }, get:function(a) { + return this._shape; + }, enumerable:!0}); + this.registered_node_types[a] = b; + b.constructor.name && (this.Nodes[c] = b); + b.prototype.onPropertyChange && console.warn("LiteGraph node class " + a + " has onPropertyChange method, it must be called onPropertyChanged with d at the end"); + if (b.supported_extensions) { + for (f in b.supported_extensions) { + this.node_types_by_file_extension[b.supported_extensions[f].toLowerCase()] = b; + } + } + }, wrapFunctionAsNode:function(a, b, c, e) { + for (var f = Array(b.length), k = "", n = l.getParameterNames(b), h = 0; h < n.length; ++h) { + k += "this.addInput('" + n[h] + "'," + (c && c[h] ? "'" + c[h] + "'" : "0") + ");\n"; + } + c = Function(k + ("this.addOutput('out'," + (e ? "'" + e + "'" : 0) + ");\n")); + c.title = a.split("/").pop(); + c.desc = "Generated from " + b.name; + c.prototype.onExecute = function() { + for (var a = 0; a < f.length; ++a) { + f[a] = this.getInputData(a); + } + a = b.apply(this, f); + this.setOutputData(0, a); + }; + this.registerNodeType(a, c); + }, addNodeMethod:function(a, b) { + m.prototype[a] = b; + for (var c in this.registered_node_types) { + var e = this.registered_node_types[c]; + e.prototype[a] && (e.prototype["_" + a] = e.prototype[a]); + e.prototype[a] = b; + } + }, createNode:function(a, b, c) { + var e = this.registered_node_types[a]; + if (!e) { + return l.debug && console.log('GraphNode type "' + a + '" not registered.'), null; + } + b = b || e.title || a; + e = new e(b); + e.type = a; + !e.title && b && (e.title = b); + e.properties || (e.properties = {}); + e.properties_info || (e.properties_info = []); + e.flags || (e.flags = {}); + e.size || (e.size = e.computeSize()); + e.pos || (e.pos = l.DEFAULT_POSITION.concat()); + e.mode || (e.mode = l.ALWAYS); + if (c) { + for (var f in c) { + e[f] = c[f]; + } + } + return e; + }, getNodeType:function(a) { + return this.registered_node_types[a]; + }, getNodeTypesInCategory:function(a, b) { + var c = [], e; + for (e in this.registered_node_types) { + var f = this.registered_node_types[e]; + b && f.filter && f.filter != b || ("" == a ? null == f.category && c.push(f) : f.category == a && c.push(f)); + } + return c; + }, getNodeTypesCategories:function() { + var a = {"":1}, b; + for (b in this.registered_node_types) { + this.registered_node_types[b].category && !this.registered_node_types[b].skip_list && (a[this.registered_node_types[b].category] = 1); + } + var c = []; + for (b in a) { + c.push(b); + } + return c; + }, reloadNodes:function(a) { + var b = document.getElementsByTagName("script"), c = [], e; + for (e in b) { + c.push(b[e]); + } + b = document.getElementsByTagName("head")[0]; + a = document.location.href + a; + for (e in c) { + var f = c[e].src; + if (f && f.substr(0, a.length) == a) { + try { + l.debug && console.log("Reloading: " + f); + var k = document.createElement("script"); + k.type = "text/javascript"; + k.src = f; + b.appendChild(k); + b.removeChild(c[e]); + } catch (n) { + if (l.throw_errors) { + throw n; + } + l.debug && console.log("Error while reloading " + f); + } + } + } + l.debug && console.log("Nodes reloaded"); + }, cloneObject:function(a, b) { + if (null == a) { + return null; + } + a = JSON.parse(JSON.stringify(a)); + if (!b) { + return a; + } + for (var c in a) { + b[c] = a[c]; + } + return b; + }, isValidConnection:function(a, b) { + if (!a || !b || a == b || a == l.EVENT && b == l.ACTION) { + return !0; + } + a = String(a); + b = String(b); + a = a.toLowerCase(); + b = b.toLowerCase(); + if (-1 == a.indexOf(",") && -1 == b.indexOf(",")) { + return a == b; + } + a = a.split(","); + b = b.split(","); + for (var c = 0; c < a.length; ++c) { + for (var e = 0; e < b.length; ++e) { + if (a[c] == b[e]) { + return !0; + } + } + } + return !1; + }, registerSearchboxExtra:function(a, b, c) { + this.searchbox_extras[b] = {type:a, desc:b, data:c}; + }}; + l.getTime = "undefined" != typeof performance ? performance.now.bind(performance) : "undefined" != typeof Date && Date.now ? Date.now.bind(Date) : "undefined" != typeof process ? function() { + var a = process.hrtime(); + return 0.001 * a[0] + 1e-6 * a[1]; + } : function() { + return (new Date).getTime(); + }; + v.LGraph = l.LGraph = d; + d.supported_types = ["number", "string", "boolean"]; + d.prototype.getSupportedTypes = function() { + return this.supported_types || d.supported_types; + }; + d.STATUS_STOPPED = 1; + d.STATUS_RUNNING = 2; + d.prototype.clear = function() { + this.stop(); + this.status = d.STATUS_STOPPED; + this.last_link_id = this.last_node_id = 1; + this._version = -1; + if (this._nodes) { + for (var a = 0; a < this._nodes.length; ++a) { + var b = this._nodes[a]; + if (b.onRemoved) { + b.onRemoved(); + } + } + } + this._nodes = []; + this._nodes_by_id = {}; + this._nodes_in_order = []; + this._nodes_executable = null; + this._groups = []; + this.links = {}; + this.iteration = 0; + this.config = {}; + this.fixedtime = this.runningtime = this.globaltime = 0; + this.elapsed_time = this.fixedtime_lapse = 0.01; + this.starttime = this.last_update_time = 0; + this.catch_errors = !0; + this.global_inputs = {}; + this.global_outputs = {}; + this.change(); + this.sendActionToCanvas("clear"); + }; + d.prototype.attachCanvas = function(a) { + if (a.constructor != h) { + throw "attachCanvas expects a LGraphCanvas instance"; + } + a.graph && a.graph != this && a.graph.detachCanvas(a); + a.graph = this; + this.list_of_graphcanvas || (this.list_of_graphcanvas = []); + this.list_of_graphcanvas.push(a); + }; + d.prototype.detachCanvas = function(a) { + if (this.list_of_graphcanvas) { + var b = this.list_of_graphcanvas.indexOf(a); + -1 != b && (a.graph = null, this.list_of_graphcanvas.splice(b, 1)); + } + }; + d.prototype.start = function(a) { + if (this.status != d.STATUS_RUNNING) { + this.status = d.STATUS_RUNNING; + if (this.onPlayEvent) { + this.onPlayEvent(); + } + this.sendEventToAllNodes("onStart"); + this.last_update_time = this.starttime = l.getTime(); + a = a || 0; + var b = this; + if (0 == a && "undefined" != typeof window && window.requestAnimationFrame) { + var c = function() { + -1 == b.execution_timer_id && (window.requestAnimationFrame(c), b.runStep(1, !this.catch_errors)); + }; + this.execution_timer_id = -1; + c(); + } else { + this.execution_timer_id = setInterval(function() { + b.runStep(1, !this.catch_errors); + }, a); + } + } + }; + d.prototype.stop = function() { + if (this.status != d.STATUS_STOPPED) { + this.status = d.STATUS_STOPPED; + if (this.onStopEvent) { + this.onStopEvent(); + } + null != this.execution_timer_id && (-1 != this.execution_timer_id && clearInterval(this.execution_timer_id), this.execution_timer_id = null); + this.sendEventToAllNodes("onStop"); + } + }; + d.prototype.runStep = function(a, b) { + a = a || 1; + var c = l.getTime(); + this.globaltime = 0.001 * (c - this.starttime); + var e = this._nodes_executable ? this._nodes_executable : this._nodes; + if (e) { + if (b) { + for (var f = 0; f < a; f++) { + for (var k = 0, n = e.length; k < n; ++k) { + var h = e[k]; + if (h.mode == l.ALWAYS && h.onExecute) { + h.onExecute(); + } + } + this.fixedtime += this.fixedtime_lapse; + if (this.onExecuteStep) { + this.onExecuteStep(); + } + } + if (this.onAfterExecute) { + this.onAfterExecute(); + } + } else { + try { + for (f = 0; f < a; f++) { + k = 0; + for (n = e.length; k < n; ++k) { + if (h = e[k], h.mode == l.ALWAYS && h.onExecute) { + h.onExecute(); + } + } + this.fixedtime += this.fixedtime_lapse; + if (this.onExecuteStep) { + this.onExecuteStep(); + } + } + if (this.onAfterExecute) { + this.onAfterExecute(); + } + this.errors_in_execution = !1; + } catch (G) { + this.errors_in_execution = !0; + if (l.throw_errors) { + throw G; + } + l.debug && console.log("Error during execution: " + G); + this.stop(); + } + } + a = l.getTime(); + c = a - c; + 0 == c && (c = 1); + this.execution_time = 0.001 * c; + this.globaltime += 0.001 * c; + this.iteration += 1; + this.elapsed_time = 0.001 * (a - this.last_update_time); + this.last_update_time = a; + } + }; + d.prototype.updateExecutionOrder = function() { + this._nodes_in_order = this.computeExecutionOrder(!1); + this._nodes_executable = []; + for (var a = 0; a < this._nodes_in_order.length; ++a) { + this._nodes_in_order[a].onExecute && this._nodes_executable.push(this._nodes_in_order[a]); + } + }; + d.prototype.computeExecutionOrder = function(a, b) { + for (var c = [], e = [], f = {}, k = {}, n = {}, h = 0, d = this._nodes.length; h < d; ++h) { + var p = this._nodes[h]; + if (!a || p.onExecute) { + f[p.id] = p; + var g = 0; + if (p.inputs) { + for (var m = 0, q = p.inputs.length; m < q; m++) { + p.inputs[m] && null != p.inputs[m].link && (g += 1); + } + } + 0 == g ? (e.push(p), b && (p._level = 1)) : (b && (p._level = 0), n[p.id] = g); + } + } + for (; 0 != e.length;) { + if (p = e.shift(), c.push(p), delete f[p.id], p.outputs) { + for (h = 0; h < p.outputs.length; h++) { + if (a = p.outputs[h], null != a && null != a.links && 0 != a.links.length) { + for (m = 0; m < a.links.length; m++) { + (d = this.links[a.links[m]]) && !k[d.id] && (g = this.getNodeById(d.target_id), null == g ? k[d.id] = !0 : (b && (!g._level || g._level <= p._level) && (g._level = p._level + 1), k[d.id] = !0, --n[g.id], 0 == n[g.id] && e.push(g))); + } + } + } + } + } + for (h in f) { + c.push(f[h]); + } + c.length != this._nodes.length && l.debug && console.warn("something went wrong, nodes missing"); + d = c.length; + for (h = 0; h < d; ++h) { + c[h].order = h; + } + c = c.sort(function(a, b) { + var c = a.constructor.priority || a.priority || 0, e = b.constructor.priority || b.priority || 0; + return c == e ? a.order - b.order : c - e; + }); + for (h = 0; h < d; ++h) { + c[h].order = h; + } + return c; + }; + d.prototype.getAncestors = function(a) { + for (var b = [], c = [a], e = {}; c.length;) { + var f = c.shift(); + if (f.inputs) { + e[f.id] || f == a || (e[f.id] = !0, b.push(f)); + for (var k = 0; k < f.inputs.length; ++k) { + var n = f.getInputNode(k); + n && -1 == b.indexOf(n) && c.push(n); + } + } + } + b.sort(function(a, b) { + return a.order - b.order; + }); + return b; + }; + d.prototype.arrange = function(a) { + a = a || 40; + for (var b = this.computeExecutionOrder(!1, !0), c = [], e = 0; e < b.length; ++e) { + var f = b[e], k = f._level || 1; + c[k] || (c[k] = []); + c[k].push(f); + } + b = a; + for (e = 0; e < c.length; ++e) { + if (k = c[e]) { + for (var n = 100, h = a, l = 0; l < k.length; ++l) { + f = k[l], f.pos[0] = b, f.pos[1] = h, f.size[0] > n && (n = f.size[0]), h += f.size[1] + a; + } + b += n + a; + } + } + this.setDirtyCanvas(!0, !0); + }; + d.prototype.getTime = function() { + return this.globaltime; + }; + d.prototype.getFixedTime = function() { + return this.fixedtime; + }; + d.prototype.getElapsedTime = function() { + return this.elapsed_time; + }; + d.prototype.sendEventToAllNodes = function(a, b, c) { + c = c || l.ALWAYS; + var e = this._nodes_in_order ? this._nodes_in_order : this._nodes; + if (e) { + for (var f = 0, k = e.length; f < k; ++f) { + var n = e[f]; + if (n[a] && n.mode == c) { + if (void 0 === b) { + n[a](); + } else { + if (b && b.constructor === Array) { + n[a].apply(n, b); + } else { + n[a](b); + } + } + } + } + } + }; + d.prototype.sendActionToCanvas = function(a, b) { + if (this.list_of_graphcanvas) { + for (var c = 0; c < this.list_of_graphcanvas.length; ++c) { + var e = this.list_of_graphcanvas[c]; + e[a] && e[a].apply(e, b); + } + } + }; + d.prototype.add = function(a, b) { + if (a) { + if (a.constructor === q) { + this._groups.push(a), this.setDirtyCanvas(!0), this.change(), a.graph = this, this._version++; + } else { + -1 != a.id && null != this._nodes_by_id[a.id] && (console.warn("LiteGraph: there is already a node with this ID, changing it"), a.id = ++this.last_node_id); + if (this._nodes.length >= l.MAX_NUMBER_OF_NODES) { + throw "LiteGraph: max number of nodes in a graph reached"; + } + null == a.id || -1 == a.id ? a.id = ++this.last_node_id : this.last_node_id < a.id && (this.last_node_id = a.id); + a.graph = this; + this._version++; + this._nodes.push(a); + this._nodes_by_id[a.id] = a; + if (a.onAdded) { + a.onAdded(this); + } + this.config.align_to_grid && a.alignToGrid(); + b || this.updateExecutionOrder(); + if (this.onNodeAdded) { + this.onNodeAdded(a); + } + this.setDirtyCanvas(!0); + this.change(); + return a; + } + } + }; + d.prototype.remove = function(a) { + if (a.constructor === l.LGraphGroup) { + var b = this._groups.indexOf(a); + -1 != b && this._groups.splice(b, 1); + a.graph = null; + this._version++; + this.setDirtyCanvas(!0, !0); + this.change(); + } else { + if (null != this._nodes_by_id[a.id] && !a.ignore_remove) { + if (a.inputs) { + for (b = 0; b < a.inputs.length; b++) { + var c = a.inputs[b]; + null != c.link && a.disconnectInput(b); + } + } + if (a.outputs) { + for (b = 0; b < a.outputs.length; b++) { + c = a.outputs[b], null != c.links && c.links.length && a.disconnectOutput(b); + } + } + if (a.onRemoved) { + a.onRemoved(); + } + a.graph = null; + this._version++; + if (this.list_of_graphcanvas) { + for (b = 0; b < this.list_of_graphcanvas.length; ++b) { + c = this.list_of_graphcanvas[b], c.selected_nodes[a.id] && delete c.selected_nodes[a.id], c.node_dragged == a && (c.node_dragged = null); + } + } + b = this._nodes.indexOf(a); + -1 != b && this._nodes.splice(b, 1); + delete this._nodes_by_id[a.id]; + if (this.onNodeRemoved) { + this.onNodeRemoved(a); + } + this.setDirtyCanvas(!0, !0); + this.change(); + this.updateExecutionOrder(); + } + } + }; + d.prototype.getNodeById = function(a) { + return null == a ? null : this._nodes_by_id[a]; + }; + d.prototype.findNodesByClass = function(a) { + for (var b = [], c = 0, e = this._nodes.length; c < e; ++c) { + this._nodes[c].constructor === a && b.push(this._nodes[c]); + } + return b; + }; + d.prototype.findNodesByType = function(a) { + a = a.toLowerCase(); + for (var b = [], c = 0, e = this._nodes.length; c < e; ++c) { + this._nodes[c].type.toLowerCase() == a && b.push(this._nodes[c]); + } + return b; + }; + d.prototype.findNodesByTitle = function(a) { + for (var b = [], c = 0, e = this._nodes.length; c < e; ++c) { + this._nodes[c].title == a && b.push(this._nodes[c]); + } + return b; + }; + d.prototype.getNodeOnPos = function(a, b, c, e) { + c = c || this._nodes; + for (var f = c.length - 1; 0 <= f; f--) { + var k = c[f]; + if (k.isPointInside(a, b, e)) { + return k; + } + } + return null; + }; + d.prototype.getGroupOnPos = function(a, b) { + for (var c = this._groups.length - 1; 0 <= c; c--) { + var e = this._groups[c]; + if (e.isPointInside(a, b, 2, !0)) { + return e; + } + } + return null; + }; + d.prototype.addGlobalInput = function(a, b, c) { + this.global_inputs[a] = {name:a, type:b, value:c}; + this._version++; + if (this.onGlobalInputAdded) { + this.onGlobalInputAdded(a, b); + } + if (this.onGlobalsChange) { + this.onGlobalsChange(); + } + }; + d.prototype.setGlobalInputData = function(a, b) { + if (a = this.global_inputs[a]) { + a.value = b; + } + }; + d.prototype.setInputData = d.prototype.setGlobalInputData; + d.prototype.getGlobalInputData = function(a) { + return (a = this.global_inputs[a]) ? a.value : null; + }; + d.prototype.renameGlobalInput = function(a, b) { + if (b != a) { + if (!this.global_inputs[a]) { + return !1; + } + if (this.global_inputs[b]) { + return console.error("there is already one input with that name"), !1; + } + this.global_inputs[b] = this.global_inputs[a]; + delete this.global_inputs[a]; + this._version++; + if (this.onGlobalInputRenamed) { + this.onGlobalInputRenamed(a, b); + } + if (this.onGlobalsChange) { + this.onGlobalsChange(); + } + } + }; + d.prototype.changeGlobalInputType = function(a, b) { + if (!this.global_inputs[a]) { + return !1; + } + if (!this.global_inputs[a].type || this.global_inputs[a].type.toLowerCase() != b.toLowerCase()) { + if (this.global_inputs[a].type = b, this._version++, this.onGlobalInputTypeChanged) { + this.onGlobalInputTypeChanged(a, b); + } + } + }; + d.prototype.removeGlobalInput = function(a) { + if (!this.global_inputs[a]) { + return !1; + } + delete this.global_inputs[a]; + this._version++; + if (this.onGlobalInputRemoved) { + this.onGlobalInputRemoved(a); + } + if (this.onGlobalsChange) { + this.onGlobalsChange(); + } + return !0; + }; + d.prototype.addGlobalOutput = function(a, b, c) { + this.global_outputs[a] = {name:a, type:b, value:c}; + this._version++; + if (this.onGlobalOutputAdded) { + this.onGlobalOutputAdded(a, b); + } + if (this.onGlobalsChange) { + this.onGlobalsChange(); + } + }; + d.prototype.setGlobalOutputData = function(a, b) { + if (a = this.global_outputs[a]) { + a.value = b; + } + }; + d.prototype.getGlobalOutputData = function(a) { + return (a = this.global_outputs[a]) ? a.value : null; + }; + d.prototype.getOutputData = d.prototype.getGlobalOutputData; + d.prototype.renameGlobalOutput = function(a, b) { + if (!this.global_outputs[a]) { + return !1; + } + if (this.global_outputs[b]) { + return console.error("there is already one output with that name"), !1; + } + this.global_outputs[b] = this.global_outputs[a]; + delete this.global_outputs[a]; + this._version++; + if (this.onGlobalOutputRenamed) { + this.onGlobalOutputRenamed(a, b); + } + if (this.onGlobalsChange) { + this.onGlobalsChange(); + } + }; + d.prototype.changeGlobalOutputType = function(a, b) { + if (!this.global_outputs[a]) { + return !1; + } + if (!this.global_outputs[a].type || this.global_outputs[a].type.toLowerCase() != b.toLowerCase()) { + if (this.global_outputs[a].type = b, this._version++, this.onGlobalOutputTypeChanged) { + this.onGlobalOutputTypeChanged(a, b); + } + } + }; + d.prototype.removeGlobalOutput = function(a) { + if (!this.global_outputs[a]) { + return !1; + } + delete this.global_outputs[a]; + this._version++; + if (this.onGlobalOutputRemoved) { + this.onGlobalOutputRemoved(a); + } + if (this.onGlobalsChange) { + this.onGlobalsChange(); + } + return !0; + }; + d.prototype.triggerInput = function(a, b) { + a = this.findNodesByTitle(a); + for (var c = 0; c < a.length; ++c) { + a[c].onTrigger(b); + } + }; + d.prototype.setCallback = function(a, b) { + a = this.findNodesByTitle(a); + for (var c = 0; c < a.length; ++c) { + a[c].setTrigger(b); + } + }; + d.prototype.connectionChange = function(a, b) { + this.updateExecutionOrder(); + if (this.onConnectionChange) { + this.onConnectionChange(a); + } + this._version++; + this.sendActionToCanvas("onConnectionChange"); + }; + d.prototype.isLive = function() { + if (!this.list_of_graphcanvas) { + return !1; + } + for (var a = 0; a < this.list_of_graphcanvas.length; ++a) { + if (this.list_of_graphcanvas[a].live_mode) { + return !0; + } + } + return !1; + }; + d.prototype.clearTriggeredSlots = function() { + for (var a in this.links) { + var b = this.links[a]; + b && b._last_time && (b._last_time = 0); + } + }; + d.prototype.change = function() { + l.debug && console.log("Graph changed"); + this.sendActionToCanvas("setDirty", [!0, !0]); + if (this.on_change) { + this.on_change(this); + } + }; + d.prototype.setDirtyCanvas = function(a, b) { + this.sendActionToCanvas("setDirty", [a, b]); + }; + d.prototype.serialize = function() { + for (var a = [], b = 0, c = this._nodes.length; b < c; ++b) { + a.push(this._nodes[b].serialize()); + } + c = []; + for (b in this.links) { + var e = this.links[b]; + c.push([e.id, e.origin_id, e.origin_slot, e.target_id, e.target_slot, e.type]); + } + e = []; + for (b = 0; b < this._groups.length; ++b) { + e.push(this._groups[b].serialize()); + } + return {last_node_id:this.last_node_id, last_link_id:this.last_link_id, nodes:a, links:c, groups:e, config:this.config}; + }; + d.prototype.configure = function(a, b) { + if (a) { + b || this.clear(); + b = a.nodes; + if (a.links && a.links.constructor === Array) { + for (var c = [], e = 0; e < a.links.length; ++e) { + var f = a.links[e]; + c[f[0]] = {id:f[0], origin_id:f[1], origin_slot:f[2], target_id:f[3], target_slot:f[4], type:f[5]}; + } + a.links = c; + } + for (e in a) { + this[e] = a[e]; + } + c = !1; + this._nodes = []; + if (b) { + e = 0; + for (f = b.length; e < f; ++e) { + var k = b[e], n = l.createNode(k.type, k.title); + n ? (n.id = k.id, this.add(n, !0)) : (l.debug && console.log("Node not found: " + k.type), c = !0); + } + e = 0; + for (f = b.length; e < f; ++e) { + k = b[e], (n = this.getNodeById(k.id)) && n.configure(k); + } + } + this._groups.length = 0; + if (a.groups) { + for (e = 0; e < a.groups.length; ++e) { + b = new l.LGraphGroup, b.configure(a.groups[e]), this.add(b); + } + } + this.updateExecutionOrder(); + this._version++; + this.setDirtyCanvas(!0, !0); + return c; + } + }; + d.prototype.load = function(a) { + var b = this, c = new XMLHttpRequest; + c.open("GET", a, !0); + c.send(null); + c.onload = function(a) { + 200 !== c.status ? console.error("Error loading graph:", c.status, c.response) : (a = JSON.parse(c.response), b.configure(a)); + }; + c.onerror = function(a) { + console.error("Error loading graph:", a); + }; + }; + d.prototype.onNodeTrace = function(a, b, c) { + }; + v.LGraphNode = l.LGraphNode = m; + m.prototype._ctor = function(a) { + this.title = a || "Unnamed"; + this.size = [l.NODE_WIDTH, 60]; + this.graph = null; + this._pos = new Float32Array(10, 10); + Object.defineProperty(this, "pos", {set:function(a) { + !a || 2 > a.length || (this._pos[0] = a[0], this._pos[1] = a[1]); + }, get:function() { + return this._pos; + }, enumerable:!0}); + this.id = -1; + this.type = null; + this.inputs = []; + this.outputs = []; + this.connections = []; + this.properties = {}; + this.properties_info = []; + this.flags = {}; + }; + m.prototype.configure = function(a) { + this.graph && this.graph._version++; + for (var b in a) { + if ("console" != b) { + if ("properties" == b) { + for (var c in a.properties) { + if (this.properties[c] = a.properties[c], this.onPropertyChanged) { + this.onPropertyChanged(c, a.properties[c]); + } + } + } else { + null != a[b] && ("object" == typeof a[b] ? this[b] && this[b].configure ? this[b].configure(a[b]) : this[b] = l.cloneObject(a[b], this[b]) : this[b] = a[b]); + } + } + } + a.title || (this.title = this.constructor.title); + if (this.onConnectionsChange) { + if (this.inputs) { + for (var e = 0; e < this.inputs.length; ++e) { + c = this.inputs[e]; + var f = this.graph ? this.graph.links[c.link] : null; + this.onConnectionsChange(l.INPUT, e, !0, f, c); + } + } + if (this.outputs) { + for (e = 0; e < this.outputs.length; ++e) { + if (c = this.outputs[e], c.links) { + for (b = 0; b < c.links.length; ++b) { + f = this.graph ? this.graph.links[c.links[b]] : null, this.onConnectionsChange(l.OUTPUT, e, !0, f, c); + } + } + } + } + } + for (e in this.inputs) { + c = this.inputs[e], c.link && c.link.length && (f = c.link, "object" == typeof f && (c.link = f[0], this.graph && (this.graph.links[f[0]] = {id:f[0], origin_id:f[1], origin_slot:f[2], target_id:f[3], target_slot:f[4]}))); + } + for (e in this.outputs) { + if (c = this.outputs[e], c.links && 0 != c.links.length) { + for (b in c.links) { + f = c.links[b], "object" == typeof f && (c.links[b] = f[0]); + } + } + } + if (this.onConfigure) { + this.onConfigure(a); + } + }; + m.prototype.serialize = function() { + var a = {id:this.id, type:this.type, pos:this.pos, size:this.size, flags:l.cloneObject(this.flags), mode:this.mode}; + this.inputs && (a.inputs = this.inputs); + if (this.outputs) { + for (var b = 0; b < this.outputs.length; b++) { + delete this.outputs[b]._data; + } + a.outputs = this.outputs; + } + this.title && this.title != this.constructor.title && (a.title = this.title); + this.properties && (a.properties = l.cloneObject(this.properties)); + a.type || (a.type = this.constructor.type); + this.color && (a.color = this.color); + this.bgcolor && (a.bgcolor = this.bgcolor); + this.boxcolor && (a.boxcolor = this.boxcolor); + this.shape && (a.shape = this.shape); + this.onSerialize && this.onSerialize(a) && console.warn("node onSerialize shouldnt return anything, data should be stored in the object pass in the first parameter"); + return a; + }; + m.prototype.clone = function() { + var a = l.createNode(this.type), b = l.cloneObject(this.serialize()); + if (b.inputs) { + for (var c = 0; c < b.inputs.length; ++c) { + b.inputs[c].link = null; + } + } + if (b.outputs) { + for (c = 0; c < b.outputs.length; ++c) { + b.outputs[c].links && (b.outputs[c].links.length = 0); + } + } + delete b.id; + a.configure(b); + return a; + }; + m.prototype.toString = function() { + return JSON.stringify(this.serialize()); + }; + m.prototype.getTitle = function() { + return this.title || this.constructor.title; + }; + m.prototype.setOutputData = function(a, b) { + if (this.outputs && !(-1 == a || a >= this.outputs.length)) { + var c = this.outputs[a]; + if (c && (c._data = b, this.outputs[a].links)) { + for (c = 0; c < this.outputs[a].links.length; c++) { + this.graph.links[this.outputs[a].links[c]].data = b; + } + } + } + }; + m.prototype.getInputData = function(a, b) { + if (this.inputs && !(a >= this.inputs.length || null == this.inputs[a].link)) { + a = this.graph.links[this.inputs[a].link]; + if (!a) { + return null; + } + if (!b) { + return a.data; + } + b = this.graph.getNodeById(a.origin_id); + if (!b) { + return a.data; + } + if (b.updateOutputData) { + b.updateOutputData(a.origin_slot); + } else { + if (b.onExecute) { + b.onExecute(); + } + } + return a.data; + } + }; + m.prototype.getInputDataByName = function(a, b) { + a = this.findInputSlot(a); + return -1 == a ? null : this.getInputData(a, b); + }; + m.prototype.isInputConnected = function(a) { + return this.inputs ? a < this.inputs.length && null != this.inputs[a].link : !1; + }; + m.prototype.getInputInfo = function(a) { + return this.inputs ? a < this.inputs.length ? this.inputs[a] : null : null; + }; + m.prototype.getInputNode = function(a) { + if (!this.inputs || a >= this.inputs.length) { + return null; + } + a = this.inputs[a]; + return a && null !== a.link ? (a = this.graph.links[a.link]) ? this.graph.getNodeById(a.origin_id) : null : null; + }; + m.prototype.getInputOrProperty = function(a) { + if (!this.inputs || !this.inputs.length) { + return this.properties ? this.properties[a] : null; + } + for (var b = 0, c = this.inputs.length; b < c; ++b) { + var e = this.inputs[b]; + if (a == e.name && null != e.link && (e = this.graph.links[e.link])) { + return e.data; + } + } + return this.properties[a]; + }; + m.prototype.getOutputData = function(a) { + return !this.outputs || a >= this.outputs.length ? null : this.outputs[a]._data; + }; + m.prototype.getOutputInfo = function(a) { + return this.outputs ? a < this.outputs.length ? this.outputs[a] : null : null; + }; + m.prototype.isOutputConnected = function(a) { + return this.outputs ? a < this.outputs.length && this.outputs[a].links && this.outputs[a].links.length : !1; + }; + m.prototype.isAnyOutputConnected = function() { + if (!this.outputs) { + return !1; + } + for (var a = 0; a < this.outputs.length; ++a) { + if (this.outputs[a].links && this.outputs[a].links.length) { + return !0; + } + } + return !1; + }; + m.prototype.getOutputNodes = function(a) { + if (!this.outputs || 0 == this.outputs.length || a >= this.outputs.length) { + return null; + } + a = this.outputs[a]; + if (!a.links || 0 == a.links.length) { + return null; + } + for (var b = [], c = 0; c < a.links.length; c++) { + var e = this.graph.links[a.links[c]]; + e && (e = this.graph.getNodeById(e.target_id)) && b.push(e); + } + return b; + }; + m.prototype.trigger = function(a, b) { + if (this.outputs && this.outputs.length) { + this.graph && (this.graph._last_trigger_time = l.getTime()); + for (var c = 0; c < this.outputs.length; ++c) { + var e = this.outputs[c]; + !e || e.type !== l.EVENT || a && e.name != a || this.triggerSlot(c, b); + } + } + }; + m.prototype.triggerSlot = function(a, b, c) { + if (this.outputs && (a = this.outputs[a]) && (a = a.links) && a.length) { + this.graph && (this.graph._last_trigger_time = l.getTime()); + for (var e = 0; e < a.length; ++e) { + var f = a[e]; + if (null == c || c == f) { + var k = this.graph.links[a[e]]; + if (k && (k._last_time = l.getTime(), f = this.graph.getNodeById(k.target_id))) { + if (k = f.inputs[k.target_slot], f.onAction) { + f.onAction(k.name, b); + } else { + if (f.mode === l.ON_TRIGGER && f.onExecute) { + f.onExecute(b); + } + } + } + } + } + } + }; + m.prototype.clearTriggeredSlot = function(a, b) { + if (this.outputs && (a = this.outputs[a]) && (a = a.links) && a.length) { + for (var c = 0; c < a.length; ++c) { + var e = a[c]; + if (null == b || b == e) { + if (e = this.graph.links[a[c]]) { + e._last_time = 0; + } + } + } + } + }; + m.prototype.addProperty = function(a, b, c, e) { + c = {name:a, type:c, default_value:b}; + if (e) { + for (var f in e) { + c[f] = e[f]; + } + } + this.properties_info || (this.properties_info = []); + this.properties_info.push(c); + this.properties || (this.properties = {}); + this.properties[a] = b; + return c; + }; + m.prototype.addOutput = function(a, b, c) { + a = {name:a, type:b, links:null}; + if (c) { + for (var e in c) { + a[e] = c[e]; + } + } + this.outputs || (this.outputs = []); + this.outputs.push(a); + if (this.onOutputAdded) { + this.onOutputAdded(a); + } + this.size = this.computeSize(); + this.setDirtyCanvas(!0, !0); + return a; + }; + m.prototype.addOutputs = function(a) { + for (var b = 0; b < a.length; ++b) { + var c = a[b], e = {name:c[0], type:c[1], link:null}; + if (a[2]) { + for (var f in c[2]) { + e[f] = c[2][f]; + } + } + this.outputs || (this.outputs = []); + this.outputs.push(e); + if (this.onOutputAdded) { + this.onOutputAdded(e); + } + } + this.size = this.computeSize(); + this.setDirtyCanvas(!0, !0); + }; + m.prototype.removeOutput = function(a) { + this.disconnectOutput(a); + this.outputs.splice(a, 1); + for (var b = a; b < this.outputs.length; ++b) { + if (this.outputs[b] && this.outputs[b].links) { + for (var c = this.outputs[b].links, e = 0; e < c.length; ++e) { + var f = this.graph.links[c[e]]; + f && --f.origin_slot; + } + } + } + this.size = this.computeSize(); + if (this.onOutputRemoved) { + this.onOutputRemoved(a); + } + this.setDirtyCanvas(!0, !0); + }; + m.prototype.addInput = function(a, b, c) { + a = {name:a, type:b || 0, link:null}; + if (c) { + for (var e in c) { + a[e] = c[e]; + } + } + this.inputs || (this.inputs = []); + this.inputs.push(a); + this.size = this.computeSize(); + if (this.onInputAdded) { + this.onInputAdded(a); + } + this.setDirtyCanvas(!0, !0); + return a; + }; + m.prototype.addInputs = function(a) { + for (var b = 0; b < a.length; ++b) { + var c = a[b], e = {name:c[0], type:c[1], link:null}; + if (a[2]) { + for (var f in c[2]) { + e[f] = c[2][f]; + } + } + this.inputs || (this.inputs = []); + this.inputs.push(e); + if (this.onInputAdded) { + this.onInputAdded(e); + } + } + this.size = this.computeSize(); + this.setDirtyCanvas(!0, !0); + }; + m.prototype.removeInput = function(a) { + this.disconnectInput(a); + this.inputs.splice(a, 1); + for (var b = a; b < this.inputs.length; ++b) { + if (this.inputs[b]) { + var c = this.graph.links[this.inputs[b].link]; + c && --c.target_slot; + } + } + this.size = this.computeSize(); + if (this.onInputRemoved) { + this.onInputRemoved(a); + } + this.setDirtyCanvas(!0, !0); + }; + m.prototype.addConnection = function(a, b, c, e) { + a = {name:a, type:b, pos:c, direction:e, links:null}; + this.connections.push(a); + return a; + }; + m.prototype.computeSize = function(a, b) { + function c(a) { + return a ? e * a.length * 0.6 : 0; + } + a = Math.max(this.inputs ? this.inputs.length : 1, this.outputs ? this.outputs.length : 1); + b = b || new Float32Array([0, 0]); + a = Math.max(a, 1); + var e = l.NODE_TEXT_SIZE; + b[1] = (this.constructor.slot_start_y || 0) + a * (e + 1) + 4; + this.widgets && this.widgets.length && (b[1] += this.widgets.length * (l.NODE_WIDGET_HEIGHT + 4) + 8); + a = c(this.title); + var f = 0, k = 0; + if (this.inputs) { + for (var n = 0, h = this.inputs.length; n < h; ++n) { + var p = this.inputs[n]; + p = p.label || p.name || ""; + p = c(p); + f < p && (f = p); + } + } + if (this.outputs) { + for (n = 0, h = this.outputs.length; n < h; ++n) { + p = this.outputs[n], p = p.label || p.name || "", p = c(p), k < p && (k = p); + } + } + b[0] = Math.max(f + k + 10, a); + b[0] = Math.max(b[0], l.NODE_WIDTH); + this.widgets && this.widgets.length && (b[0] = Math.max(b[0], 1.5 * l.NODE_WIDTH)); + if (this.onResize) { + this.onResize(b); + } + return b; + }; + m.prototype.addWidget = function(a, b, c, e, f) { + this.widgets || (this.widgets = []); + b = {type:a.toLowerCase(), name:b, value:c, callback:e, options:f || {}}; + void 0 !== b.options.y && (b.y = b.options.y); + e || console.warn("LiteGraph addWidget('button',...) without a callback"); + if ("combo" == a && !b.options.values) { + throw "LiteGraph addWidget('combo',...) requires to pass values in options: { values:['red','blue'] }"; + } + this.widgets.push(b); + return b; + }; + m.prototype.addCustomWidget = function(a) { + this.widgets || (this.widgets = []); + this.widgets.push(a); + return a; + }; + m.prototype.getBounding = function(a) { + a = a || new Float32Array(4); + a[0] = this.pos[0] - 4; + a[1] = this.pos[1] - l.NODE_TITLE_HEIGHT; + a[2] = this.size[0] + 4; + a[3] = this.size[1] + l.NODE_TITLE_HEIGHT; + if (this.onBounding) { + this.onBounding(a); + } + return a; + }; + m.prototype.isPointInside = function(a, b, c, e) { + c = c || 0; + var f = this.graph && this.graph.isLive() ? 0 : 20; + e && (f = 0); + if (this.flags && this.flags.collapsed) { + if (t(a, b, this.pos[0] - c, this.pos[1] - l.NODE_TITLE_HEIGHT - c, (this._collapsed_width || l.NODE_COLLAPSED_WIDTH) + 2 * c, l.NODE_TITLE_HEIGHT + 2 * c)) { + return !0; + } + } else { + if (this.pos[0] - 4 - c < a && this.pos[0] + this.size[0] + 4 + c > a && this.pos[1] - f - c < b && this.pos[1] + this.size[1] + c > b) { + return !0; + } + } + return !1; + }; + m.prototype.getSlotInPosition = function(a, b) { + var c = new Float32Array(2); + if (this.inputs) { + for (var e = 0, f = this.inputs.length; e < f; ++e) { + var k = this.inputs[e]; + this.getConnectionPos(!0, e, c); + if (t(a, b, c[0] - 10, c[1] - 5, 20, 10)) { + return {input:k, slot:e, link_pos:c, locked:k.locked}; + } + } + } + if (this.outputs) { + for (e = 0, f = this.outputs.length; e < f; ++e) { + if (k = this.outputs[e], this.getConnectionPos(!1, e, c), t(a, b, c[0] - 10, c[1] - 5, 20, 10)) { + return {output:k, slot:e, link_pos:c, locked:k.locked}; + } + } + } + return null; + }; + m.prototype.findInputSlot = function(a) { + if (!this.inputs) { + return -1; + } + for (var b = 0, c = this.inputs.length; b < c; ++b) { + if (a == this.inputs[b].name) { + return b; + } + } + return -1; + }; + m.prototype.findOutputSlot = function(a) { + if (!this.outputs) { + return -1; + } + for (var b = 0, c = this.outputs.length; b < c; ++b) { + if (a == this.outputs[b].name) { + return b; + } + } + return -1; + }; + m.prototype.connect = function(a, b, c) { + c = c || 0; + if (!this.graph) { + return console.log("Connect: Error, node doesnt belong to any graph. Nodes must be added first to a graph before connecting them."), null; + } + if (a.constructor === String) { + if (a = this.findOutputSlot(a), -1 == a) { + return l.debug && console.log("Connect: Error, no slot of name " + a), null; + } + } else { + if (!this.outputs || a >= this.outputs.length) { + return l.debug && console.log("Connect: Error, slot number not found"), null; + } + } + b && b.constructor === Number && (b = this.graph.getNodeById(b)); + if (!b) { + throw "target node is null"; + } + if (b == this) { + return null; + } + if (c.constructor === String) { + if (c = b.findInputSlot(c), -1 == c) { + return l.debug && console.log("Connect: Error, no slot of name " + c), null; + } + } else { + if (c === l.EVENT) { + return null; + } + if (!b.inputs || c >= b.inputs.length) { + return l.debug && console.log("Connect: Error, slot number not found"), null; + } + } + null != b.inputs[c].link && b.disconnectInput(c); + var e = this.outputs[a]; + if (b.onConnectInput && !1 === b.onConnectInput(c, e.type, e)) { + return null; + } + var f = b.inputs[c], k = null; + if (l.isValidConnection(e.type, f.type)) { + k = {id:this.graph.last_link_id++, type:f.type, origin_id:this.id, origin_slot:a, target_id:b.id, target_slot:c}; + this.graph.links[k.id] = k; + null == e.links && (e.links = []); + e.links.push(k.id); + b.inputs[c].link = k.id; + this.graph && this.graph._version++; + if (this.onConnectionsChange) { + this.onConnectionsChange(l.OUTPUT, a, !0, k, e); + } + if (b.onConnectionsChange) { + b.onConnectionsChange(l.INPUT, c, !0, k, f); + } + this.graph && this.graph.onNodeConnectionChange && (this.graph.onNodeConnectionChange(l.INPUT, b, c, this, a), this.graph.onNodeConnectionChange(l.OUTPUT, this, a, b, c)); + } + this.setDirtyCanvas(!1, !0); + this.graph.connectionChange(this, k); + return k; + }; + m.prototype.disconnectOutput = function(a, b) { + if (a.constructor === String) { + if (a = this.findOutputSlot(a), -1 == a) { + return l.debug && console.log("Connect: Error, no slot of name " + a), !1; + } + } else { + if (!this.outputs || a >= this.outputs.length) { + return l.debug && console.log("Connect: Error, slot number not found"), !1; + } + } + var c = this.outputs[a]; + if (!c || !c.links || 0 == c.links.length) { + return !1; + } + if (b) { + b.constructor === Number && (b = this.graph.getNodeById(b)); + if (!b) { + throw "Target Node not found"; + } + for (var e = 0, f = c.links.length; e < f; e++) { + var k = c.links[e], n = this.graph.links[k]; + if (n.target_id == b.id) { + c.links.splice(e, 1); + var h = b.inputs[n.target_slot]; + h.link = null; + delete this.graph.links[k]; + this.graph && this.graph._version++; + if (b.onConnectionsChange) { + b.onConnectionsChange(l.INPUT, n.target_slot, !1, n, h); + } + if (this.onConnectionsChange) { + this.onConnectionsChange(l.OUTPUT, a, !1, n, c); + } + if (this.graph && this.graph.onNodeConnectionChange) { + this.graph.onNodeConnectionChange(l.OUTPUT, this, a); + } + this.graph && this.graph.onNodeConnectionChange && (this.graph.onNodeConnectionChange(l.OUTPUT, this, a), this.graph.onNodeConnectionChange(l.INPUT, b, n.target_slot)); + break; + } + } + } else { + e = 0; + for (f = c.links.length; e < f; e++) { + if (k = c.links[e], n = this.graph.links[k]) { + b = this.graph.getNodeById(n.target_id); + this.graph && this.graph._version++; + if (b) { + h = b.inputs[n.target_slot]; + h.link = null; + if (b.onConnectionsChange) { + b.onConnectionsChange(l.INPUT, n.target_slot, !1, n, h); + } + if (this.graph && this.graph.onNodeConnectionChange) { + this.graph.onNodeConnectionChange(l.INPUT, b, n.target_slot); + } + } + delete this.graph.links[k]; + if (this.onConnectionsChange) { + this.onConnectionsChange(l.OUTPUT, a, !1, n, c); + } + this.graph && this.graph.onNodeConnectionChange && (this.graph.onNodeConnectionChange(l.OUTPUT, this, a), this.graph.onNodeConnectionChange(l.INPUT, b, n.target_slot)); + } + } + c.links = null; + } + this.setDirtyCanvas(!1, !0); + this.graph.connectionChange(this); + return !0; + }; + m.prototype.disconnectInput = function(a) { + if (a.constructor === String) { + if (a = this.findInputSlot(a), -1 == a) { + return l.debug && console.log("Connect: Error, no slot of name " + a), !1; + } + } else { + if (!this.inputs || a >= this.inputs.length) { + return l.debug && console.log("Connect: Error, slot number not found"), !1; + } + } + var b = this.inputs[a]; + if (!b) { + return !1; + } + var c = this.inputs[a].link; + this.inputs[a].link = null; + var e = this.graph.links[c]; + if (e) { + var f = this.graph.getNodeById(e.origin_id); + if (!f) { + return !1; + } + var k = f.outputs[e.origin_slot]; + if (!k || !k.links || 0 == k.links.length) { + return !1; + } + for (var n = 0, h = k.links.length; n < h; n++) { + if (k.links[n] == c) { + k.links.splice(n, 1); + break; + } + } + delete this.graph.links[c]; + this.graph && this.graph._version++; + if (this.onConnectionsChange) { + this.onConnectionsChange(l.INPUT, a, !1, e, b); + } + if (f.onConnectionsChange) { + f.onConnectionsChange(l.OUTPUT, n, !1, e, k); + } + this.graph && this.graph.onNodeConnectionChange && (this.graph.onNodeConnectionChange(l.OUTPUT, f, n), this.graph.onNodeConnectionChange(l.INPUT, this, a)); + } + this.setDirtyCanvas(!1, !0); + this.graph.connectionChange(this); + return !0; + }; + m.prototype.getConnectionPos = function(a, b, c) { + c = c || new Float32Array(2); + var e = 0; + a && this.inputs && (e = this.inputs.length); + !a && this.outputs && (e = this.outputs.length); + if (this.flags.collapsed) { + return b = this._collapsed_width || l.NODE_COLLAPSED_WIDTH, this.flags.horizontal ? (c[0] = this.pos[0] + 0.5 * b, c[1] = a ? this.pos[1] - l.NODE_TITLE_HEIGHT : this.pos[1]) : (c[0] = a ? this.pos[0] : this.pos[0] + b, c[1] = this.pos[1] - 0.5 * l.NODE_TITLE_HEIGHT), c; + } + if (a && -1 == b) { + return c[0] = this.pos[0] + 10, c[1] = this.pos[1] + 10, c; + } + if (a && e > b && this.inputs[b].pos) { + return c[0] = this.pos[0] + this.inputs[b].pos[0], c[1] = this.pos[1] + this.inputs[b].pos[1], c; + } + if (!a && e > b && this.outputs[b].pos) { + return c[0] = this.pos[0] + this.outputs[b].pos[0], c[1] = this.pos[1] + this.outputs[b].pos[1], c; + } + if (this.flags.horizontal) { + return c[0] = this.pos[0] + this.size[0] / e * (b + 0.5), c[1] = a ? this.pos[1] - l.NODE_TITLE_HEIGHT : this.pos[1] + this.size[1], c; + } + c[0] = a ? this.pos[0] : this.pos[0] + this.size[0] + 1; + c[1] = this.pos[1] + 10 + b * l.NODE_SLOT_HEIGHT + (this.constructor.slot_start_y || 0); + return c; + }; + m.prototype.alignToGrid = function() { + this.pos[0] = l.CANVAS_GRID_SIZE * Math.round(this.pos[0] / l.CANVAS_GRID_SIZE); + this.pos[1] = l.CANVAS_GRID_SIZE * Math.round(this.pos[1] / l.CANVAS_GRID_SIZE); + }; + m.prototype.trace = function(a) { + this.console || (this.console = []); + this.console.push(a); + this.console.length > m.MAX_CONSOLE && this.console.shift(); + this.graph.onNodeTrace(this, a); + }; + m.prototype.setDirtyCanvas = function(a, b) { + this.graph && this.graph.sendActionToCanvas("setDirty", [a, b]); + }; + m.prototype.loadImage = function(a) { + var b = new Image; + b.src = l.node_images_path + a; + b.ready = !1; + var c = this; + b.onload = function() { + this.ready = !0; + c.setDirtyCanvas(!0); + }; + return b; + }; + m.prototype.captureInput = function(a) { + if (this.graph && this.graph.list_of_graphcanvas) { + for (var b = this.graph.list_of_graphcanvas, c = 0; c < b.length; ++c) { + var e = b[c]; + if (a || e.node_capturing_input == this) { + e.node_capturing_input = a ? this : null; + } + } + } + }; + m.prototype.collapse = function(a) { + this.graph._version++; + if (!1 !== this.constructor.collapsable || a) { + this.flags.collapsed = this.flags.collapsed ? !1 : !0, this.setDirtyCanvas(!0, !0); + } + }; + m.prototype.pin = function(a) { + this.graph._version++; + this.flags.pinned = void 0 === a ? !this.flags.pinned : a; + }; + m.prototype.localToScreen = function(a, b, c) { + return [(a + this.pos[0]) * c.scale + c.offset[0], (b + this.pos[1]) * c.scale + c.offset[1]]; + }; + v.LGraphGroup = l.LGraphGroup = q; + q.prototype._ctor = function(a) { + this.title = a || "Group"; + this.font_size = 24; + this.color = h.node_colors.pale_blue ? h.node_colors.pale_blue.groupcolor : "#AAA"; + this._bounding = new Float32Array([10, 10, 140, 80]); + this._pos = this._bounding.subarray(0, 2); + this._size = this._bounding.subarray(2, 4); + this._nodes = []; + this.graph = null; + Object.defineProperty(this, "pos", {set:function(a) { + !a || 2 > a.length || (this._pos[0] = a[0], this._pos[1] = a[1]); + }, get:function() { + return this._pos; + }, enumerable:!0}); + Object.defineProperty(this, "size", {set:function(a) { + !a || 2 > a.length || (this._size[0] = Math.max(140, a[0]), this._size[1] = Math.max(80, a[1])); + }, get:function() { + return this._size; + }, enumerable:!0}); + }; + q.prototype.configure = function(a) { + this.title = a.title; + this._bounding.set(a.bounding); + this.color = a.color; + this.font = a.font; + }; + q.prototype.serialize = function() { + var a = this._bounding; + return {title:this.title, bounding:[Math.round(a[0]), Math.round(a[1]), Math.round(a[2]), Math.round(a[3])], color:this.color, font:this.font}; + }; + q.prototype.move = function(a, b, c) { + this._pos[0] += a; + this._pos[1] += b; + if (!c) { + for (c = 0; c < this._nodes.length; ++c) { + var e = this._nodes[c]; + e.pos[0] += a; + e.pos[1] += b; + } + } + }; + q.prototype.recomputeInsideNodes = function() { + this._nodes.length = 0; + for (var a = this.graph._nodes, b = new Float32Array(4), c = 0; c < a.length; ++c) { + var e = a[c]; + e.getBounding(b); + w(this._bounding, b) && this._nodes.push(e); + } + }; + q.prototype.isPointInside = m.prototype.isPointInside; + q.prototype.setDirtyCanvas = m.prototype.setDirtyCanvas; + v.LGraphCanvas = l.LGraphCanvas = h; + h.link_type_colors = {"-1":"#F85", number:"#AAA", node:"#DCA"}; + h.gradients = {}; + h.prototype.clear = function() { + this.fps = this.render_time = this.last_draw_time = this.frame = 0; + this.scale = 1; + this.offset = [0, 0]; + this.dragging_rectangle = null; + this.selected_nodes = {}; + this.selected_group = null; + this.visible_nodes = []; + this.connecting_node = this.node_capturing_input = this.node_over = this.node_dragged = null; + this.highlighted_links = {}; + this.dirty_bgcanvas = this.dirty_canvas = !0; + this.node_widget = this.node_in_panel = this.dirty_area = null; + this.last_mouse = [0, 0]; + this.last_mouseclick = 0; + this.visible_area.set([0, 0, 0, 0]); + if (this.onClear) { + this.onClear(); + } + }; + h.prototype.setGraph = function(a, b) { + this.graph != a && (b || this.clear(), !a && this.graph ? this.graph.detachCanvas(this) : (a.attachCanvas(this), this.setDirty(!0, !0))); + }; + h.prototype.openSubgraph = function(a) { + if (!a) { + throw "graph cannot be null"; + } + if (this.graph == a) { + throw "graph cannot be the same"; + } + this.clear(); + this.graph && (this._graph_stack || (this._graph_stack = []), this._graph_stack.push(this.graph)); + a.attachCanvas(this); + this.setDirty(!0, !0); + }; + h.prototype.closeSubgraph = function() { + if (this._graph_stack && 0 != this._graph_stack.length) { + var a = this.graph._subgraph_node, b = this._graph_stack.pop(); + this.selected_nodes = {}; + this.highlighted_links = {}; + b.attachCanvas(this); + this.setDirty(!0, !0); + a && (this.centerOnNode(a), this.selectNodes([a])); + } + }; + h.prototype.setCanvas = function(a, b) { + if (a && a.constructor === String && (a = document.getElementById(a), !a)) { + throw "Error creating LiteGraph canvas: Canvas not found"; + } + if (a !== this.canvas && (!a && this.canvas && (b || this.unbindEvents()), this.canvas = a)) { + a.className += " lgraphcanvas"; + a.data = this; + a.tabindex = "1"; + this.bgcanvas = null; + this.bgcanvas || (this.bgcanvas = document.createElement("canvas"), this.bgcanvas.width = this.canvas.width, this.bgcanvas.height = this.canvas.height); + if (null == a.getContext) { + if ("canvas" != a.localName) { + throw "Element supplied for LGraphCanvas must be a