1(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.TF = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 2var sprintf = require('sprintf'); 3module.exports = format; 4 5function format (x, bytes) { 6 if (bytes === undefined) bytes = 8; 7 var rfmt = '%' + bytes + '.' + bytes + 's'; 8 9 if (bytes <= 0) return undefined; 10 if (isNaN(x)) return sprintf(rfmt, 'NaN'); 11 if (x === Infinity) { 12 if (bytes === 1) return undefined; 13 return sprintf(rfmt, bytes >= 9 ? 'Infinity' : ' Inf').slice(0, bytes); 14 } 15 if (x === -Infinity) { 16 if (bytes === 1) return undefined; 17 return sprintf(rfmt, bytes >= 9 ? '-Infinity' : '-Inf').slice(0, bytes); 18 } 19 return packf(x, bytes); 20}; 21 22function sci (x, bytes) { 23 var n = Math.max(1, log10f(Math.abs(x))); 24 var sz = log10f(Math.abs(n)); 25 26 var b = Math.pow(10,bytes+1); 27 if (Math.abs(x) < 1) { 28 x = Math.round(x * b) / b; 29 } 30 else { 31 var tn = Math.pow(10, n + 1); 32 x = Math.round(x / tn * b) / b * tn; 33 } 34 35 var s; 36 if (bytes - sz - 6 === -1) { 37 x = Math.round(x / Math.pow(10, n)); 38 x = x * Math.pow(10, n); 39 s = sprintf('%1e', x).replace(/\.[^e]+/, ''); 40 } 41 else if (bytes - sz - 6 < 0) return undefined; 42 else { 43 s = sprintf('%.' + (bytes - sz - 6) + 'e', x); 44 } 45 if (x > 0) s = ' ' + s; 46 return pad(s, bytes); 47} 48 49function pad (s, bytes) { 50 return Array(Math.max(0, bytes - s.length + 1)).join(' ') + s; 51} 52 53function log10f (n) { 54 return Math.floor(Math.log(n) / Math.log(10)); 55} 56 57function packf (x, bytes) { 58 var lbytes = Math.max(1, Math.floor((bytes - 2) / 2)); 59 var rbytes = bytes - lbytes - 2; 60 61 if (x === 0 && bytes < 4) { 62 return pad('0', bytes); 63 } 64 else if (x === 0) { 65 return pad('0.' + Array(rbytes+1).join('0'), bytes); 66 } 67 68 if (rbytes <= 0) { 69 var s = sprintf('%' + lbytes + 'f', x); 70 if (x >= 0) s = ' ' + s; 71 if (s.length > bytes) return undefined; 72 return pad(s, bytes); 73 } 74 if (Math.abs(x) < Math.pow(10,1-rbytes)) return sci(x, bytes); 75 76 var b = Math.pow(10,bytes-3); 77 var tn = Math.pow(10, log10f(Math.abs(x))); 78 var xr = Math.round(x / tn * b) / b * tn; 79 80 var s = sprintf('%' + lbytes + '.' + rbytes + 'f', xr); 81 if (xr > 0) s = ' ' + s; 82 s = s.slice(0, bytes); 83 var r = s.split('.')[1]; 84 if (!r || r.length < 1) return sci(xr, bytes); 85 return pad(s, bytes).slice(0, bytes); 86} 87 88},{"sprintf":6}],2:[function(require,module,exports){ 89"use strict" 90 91function iota(n) { 92 var result = new Array(n) 93 for(var i=0; i<n; ++i) { 94 result[i] = i 95 } 96 return result 97} 98 99module.exports = iota 100},{}],3:[function(require,module,exports){ 101/*! 102 * Determine if an object is a Buffer 103 * 104 * @author Feross Aboukhadijeh <[email protected]> <http://feross.org> 105 * @license MIT 106 */ 107 108// The _isBuffer check is for Safari 5-7 support, because it's missing 109// Object.prototype.constructor. Remove this eventually 110module.exports = function (obj) { 111 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) 112} 113 114function isBuffer (obj) { 115 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) 116} 117 118// For Node v0.10 support. Remove this eventually. 119function isSlowBuffer (obj) { 120 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) 121} 122 123},{}],4:[function(require,module,exports){ 124var showf = require('fixed-width-float'); 125var ndarray = require('ndarray'); 126 127module.exports = function (m, opts) { 128 if (!opts) opts = {}; 129 if (typeof opts === 'number') opts = { width: opts }; 130 if (!opts.width) opts.width = 8; 131 132 if (m.dimension === undefined) { 133 m = ndarray(m); 134 } 135 136 if (m.dimension === 1) return d1(m, opts); 137 if (m.dimension === 2) return d2(m, opts); 138 if (m.dimension === 3) return d3(m, opts); 139 if (m.dimension === 4) return d4(m, opts); 140}; 141 142function d1 (m, opts) { 143 var terms = []; 144 for (var i = 0; i < m.shape[0]; i++) { 145 terms.push(showf(m.get(i), opts.width)); 146 } 147 return terms.join(' '); 148} 149 150function d2 (m, opts) { 151 var rows = []; 152 for (var y = 0; y < m.shape[0]; y++) { 153 rows.push(d1(m.pick(y, null), opts)); 154 } 155 return rows.join('\n'); 156} 157 158function d3 (m, opts) { 159 var rows = []; 160 for (var z = 0; z < m.shape[0]; z++) { 161 rows.push(d2(m.pick(z, null, null), opts), ''); 162 } 163 return rows.join('\n'); 164} 165 166function d4 (m, opts) { 167 var rows = [], len = 3 168 for (var w = 0; w < m.shape[0]; w++) { 169 var r = d3(m.pick(w, null, null, null), opts) 170 rows.push(r); 171 var lines = r.split('\n'); 172 for (var i = 0; i < lines.length; i++) { 173 len = Math.max(len, lines[i].length); 174 } 175 } 176 return rows.join('\n' + Array(len+1).join('-') + '\n\n'); 177} 178 179},{"fixed-width-float":1,"ndarray":5}],5:[function(require,module,exports){ 180var iota = require("iota-array") 181var isBuffer = require("is-buffer") 182 183var hasTypedArrays = ((typeof Float64Array) !== "undefined") 184 185function compare1st(a, b) { 186 return a[0] - b[0] 187} 188 189function order() { 190 var stride = this.stride
vendor: 7,024 bytes, lines 191-420
191 var terms = new Array(stride.length) 192 var i 193 for(i=0; i<terms.length; ++i) { 194 terms[i] = [Math.abs(stride[i]), i] 195 } 196 terms.sort(compare1st) 197 var result = new Array(terms.length) 198 for(i=0; i<result.length; ++i) { 199 result[i] = terms[i][1] 200 } 201 return result 202} 203 204function compileConstructor(dtype, dimension) { 205 var className = ["View", dimension, "d", dtype].join("") 206 if(dimension < 0) { 207 className = "View_Nil" + dtype 208 } 209 var useGetters = (dtype === "generic") 210 211 if(dimension === -1) { 212 //Special case for trivial arrays 213 var code = 214 "function "+className+"(a){this.data=a;};\ 215var proto="+className+".prototype;\ 216proto.dtype='"+dtype+"';\ 217proto.index=function(){return -1};\ 218proto.size=0;\ 219proto.dimension=-1;\ 220proto.shape=proto.stride=proto.order=[];\ 221proto.lo=proto.hi=proto.transpose=proto.step=\ 222function(){return new "+className+"(this.data);};\ 223proto.get=proto.set=function(){};\ 224proto.pick=function(){return null};\ 225return function construct_"+className+"(a){return new "+className+"(a);}" 226 var procedure = new Function(code) 227 return procedure() 228 } else if(dimension === 0) { 229 //Special case for 0d arrays 230 var code = 231 "function "+className+"(a,d) {\ 232this.data = a;\ 233this.offset = d\ 234};\ 235var proto="+className+".prototype;\ 236proto.dtype='"+dtype+"';\ 237proto.index=function(){return this.offset};\ 238proto.dimension=0;\ 239proto.size=1;\ 240proto.shape=\ 241proto.stride=\ 242proto.order=[];\ 243proto.lo=\ 244proto.hi=\ 245proto.transpose=\ 246proto.step=function "+className+"_copy() {\ 247return new "+className+"(this.data,this.offset)\ 248};\ 249proto.pick=function "+className+"_pick(){\ 250return TrivialArray(this.data);\ 251};\ 252proto.valueOf=proto.get=function "+className+"_get(){\ 253return "+(useGetters ? "this.data.get(this.offset)" : "this.data[this.offset]")+ 254"};\ 255proto.set=function "+className+"_set(v){\ 256return "+(useGetters ? "this.data.set(this.offset,v)" : "this.data[this.offset]=v")+"\ 257};\ 258return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}" 259 var procedure = new Function("TrivialArray", code) 260 return procedure(CACHED_CONSTRUCTORS[dtype][0]) 261 } 262 263 var code = ["'use strict'"] 264 265 //Create constructor for view 266 var indices = iota(dimension) 267 var args = indices.map(function(i) { return "i"+i }) 268 var index_str = "this.offset+" + indices.map(function(i) { 269 return "this.stride[" + i + "]*i" + i 270 }).join("+") 271 var shapeArg = indices.map(function(i) { 272 return "b"+i 273 }).join(",") 274 var strideArg = indices.map(function(i) { 275 return "c"+i 276 }).join(",") 277 code.push( 278 "function "+className+"(a," + shapeArg + "," + strideArg + ",d){this.data=a", 279 "this.shape=[" + shapeArg + "]", 280 "this.stride=[" + strideArg + "]", 281 "this.offset=d|0}", 282 "var proto="+className+".prototype", 283 "proto.dtype='"+dtype+"'", 284 "proto.dimension="+dimension) 285 286 //view.size: 287 code.push("Object.defineProperty(proto,'size',{get:function "+className+"_size(){\ 288return "+indices.map(function(i) { return "this.shape["+i+"]" }).join("*"), 289"}})") 290 291 //view.order: 292 if(dimension === 1) { 293 code.push("proto.order=[0]") 294 } else { 295 code.push("Object.defineProperty(proto,'order',{get:") 296 if(dimension < 4) { 297 code.push("function "+className+"_order(){") 298 if(dimension === 2) { 299 code.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})") 300 } else if(dimension === 3) { 301 code.push( 302"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\ 303if(s0>s1){\ 304if(s1>s2){\ 305return [2,1,0];\ 306}else if(s0>s2){\ 307return [1,2,0];\ 308}else{\ 309return [1,0,2];\ 310}\ 311}else if(s0>s2){\ 312return [2,0,1];\ 313}else if(s2>s1){\ 314return [0,1,2];\ 315}else{\ 316return [0,2,1];\ 317}}})") 318 } 319 } else { 320 code.push("ORDER})") 321 } 322 } 323 324 //view.set(i0, ..., v): 325 code.push( 326"proto.set=function "+className+"_set("+args.join(",")+",v){") 327 if(useGetters) { 328 code.push("return this.data.set("+index_str+",v)}") 329 } else { 330 code.push("return this.data["+index_str+"]=v}") 331 } 332 333 //view.get(i0, ...): 334 code.push("proto.get=function "+className+"_get("+args.join(",")+"){") 335 if(useGetters) { 336 code.push("return this.data.get("+index_str+")}") 337 } else { 338 code.push("return this.data["+index_str+"]}") 339 } 340 341 //view.index: 342 code.push( 343 "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}") 344 345 //view.hi(): 346 code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+ 347 indices.map(function(i) { 348 return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("") 349 }).join(",")+","+ 350 indices.map(function(i) { 351 return "this.stride["+i + "]" 352 }).join(",")+",this.offset)}") 353 354 //view.lo(): 355 var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" }) 356 var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" }) 357 code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(",")) 358 for(var i=0; i<dimension; ++i) { 359 code.push( 360"if(typeof i"+i+"==='number'&&i"+i+">=0){\ 361d=i"+i+"|0;\ 362b+=c"+i+"*d;\ 363a"+i+"-=d}") 364 } 365 code.push("return new "+className+"(this.data,"+ 366 indices.map(function(i) { 367 return "a"+i 368 }).join(",")+","+ 369 indices.map(function(i) { 370 return "c"+i 371 }).join(",")+",b)}") 372 373 //view.step(): 374 code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+ 375 indices.map(function(i) { 376 return "a"+i+"=this.shape["+i+"]" 377 }).join(",")+","+ 378 indices.map(function(i) { 379 return "b"+i+"=this.stride["+i+"]" 380 }).join(",")+",c=this.offset,d=0,ceil=Math.ceil") 381 for(var i=0; i<dimension; ++i) { 382 code.push( 383"if(typeof i"+i+"==='number'){\ 384d=i"+i+"|0;\ 385if(d<0){\ 386c+=b"+i+"*(a"+i+"-1);\ 387a"+i+"=ceil(-a"+i+"/d)\ 388}else{\ 389a"+i+"=ceil(a"+i+"/d)\ 390}\ 391b"+i+"*=d\ 392}") 393 } 394 code.push("return new "+className+"(this.data,"+ 395 indices.map(function(i) { 396 return "a" + i 397 }).join(",")+","+ 398 indices.map(function(i) { 399 return "b" + i 400 }).join(",")+",c)}") 401 402 //view.transpose(): 403 var tShape = new Array(dimension) 404 var tStride = new Array(dimension) 405 for(var i=0; i<dimension; ++i) { 406 tShape[i] = "a[i"+i+"]" 407 tStride[i] = "b[i"+i+"]" 408 } 409 code.push("proto.transpose=function "+className+"_transpose("+args+"){"+ 410 args.map(function(n,idx) { return n + "=(" + n + "===undefined?" + idx + ":" + n + "|0)"}).join(";"), 411 "var a=this.shape,b=this.stride;return new "+className+"(this.data,"+tShape.join(",")+","+tStride.join(",")+",this.offset)}") 412 413 //view.pick(): 414 code.push("proto.pick=function "+className+"_pick("+args+"){var a=[],b=[],c=this.offset") 415 for(var i=0; i<dimension; ++i) { 416 code.push("if(typeof i"+i+"==='number'&&i"+i+">=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}") 417 } 418 code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}") 419 420 //Add return statement
421 code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+ 422 indices.map(function(i) { 423 return "shape["+i+"]" 424 }).join(",")+","+ 425 indices.map(function(i) { 426 return "stride["+i+"]" 427 }).join(",")+",offset)}") 428 429 //Compile procedure 430 var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n")) 431 return procedure(CACHED_CONSTRUCTORS[dtype], order) 432} 433 434function arrayDType(data) { 435 if(isBuffer(data)) { 436 return "buffer" 437 } 438 if(hasTypedArrays) { 439 switch(Object.prototype.toString.call(data)) { 440 case "[object Float64Array]": 441 return "float64" 442 case "[object Float32Array]": 443 return "float32" 444 case "[object Int8Array]": 445 return "int8" 446 case "[object Int16Array]": 447 return "int16" 448 case "[object Int32Array]": 449 return "int32" 450 case "[object Uint8Array]": 451 return "uint8" 452 case "[object Uint16Array]": 453 return "uint16" 454 case "[object Uint32Array]": 455 return "uint32" 456 case "[object Uint8ClampedArray]": 457 return "uint8_clamped" 458 } 459 } 460 if(Array.isArray(data)) { 461 return "array" 462 } 463 return "generic" 464} 465 466var CACHED_CONSTRUCTORS = { 467 "float32":[], 468 "float64":[], 469 "int8":[], 470 "int16":[], 471 "int32":[], 472 "uint8":[], 473 "uint16":[], 474 "uint32":[], 475 "array":[], 476 "uint8_clamped":[], 477 "buffer":[], 478 "generic":[] 479} 480 481;(function() { 482 for(var id in CACHED_CONSTRUCTORS) { 483 CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1)) 484 } 485}); 486 487function wrappedNDArrayCtor(data, shape, stride, offset) { 488 if(data === undefined) { 489 var ctor = CACHED_CONSTRUCTORS.array[0] 490 return ctor([]) 491 } else if(typeof data === "number") { 492 data = [data] 493 } 494 if(shape === undefined) { 495 shape = [ data.length ] 496 } 497 var d = shape.length 498 if(stride === undefined) { 499 stride = new Array(d) 500 for(var i=d-1, sz=1; i>=0; --i) { 501 stride[i] = sz 502 sz *= shape[i] 503 } 504 } 505 if(offset === undefined) { 506 offset = 0 507 for(var i=0; i<d; ++i) { 508 if(stride[i] < 0) { 509 offset -= (shape[i]-1)*stride[i] 510 } 511 } 512 } 513 var dtype = arrayDType(data) 514 var ctor_list = CACHED_CONSTRUCTORS[dtype] 515 while(ctor_list.length <= d+1) { 516 ctor_list.push(compileConstructor(dtype, ctor_list.length-1)) 517 } 518 var ctor = ctor_list[d+1] 519 return ctor(data, shape, stride, offset) 520} 521 522module.exports = wrappedNDArrayCtor 523 524},{"iota-array":2,"is-buffer":3}],6:[function(require,module,exports){ 525/** 526sprintf() for JavaScript 0.7-beta1 527http://www.diveintojavascript.com/projects/javascript-sprintf 528 529Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com> 530All rights reserved. 531 532Redistribution and use in source and binary forms, with or without 533modification, are permitted provided that the following conditions are met: 534 * Redistributions of source code must retain the above copyright 535 notice, this list of conditions and the following disclaimer. 536 * Redistributions in binary form must reproduce the above copyright 537 notice, this list of conditions and the following disclaimer in the 538 documentation and/or other materials provided with the distribution. 539 * Neither the name of sprintf() for JavaScript nor the 540 names of its contributors may be used to endorse or promote products 541 derived from this software without specific prior written permission. 542 543THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 544ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 545WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 546DISCLAIMED. IN NO EVENT SHALL Alexandru Marasteanu BE LIABLE FOR ANY 547DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 548(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 549LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 550ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 551(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 552SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 553 554 555Changelog: 5562010.11.07 - 0.7-beta1-node 557 - converted it to a node.js compatible module 558 5592010.09.06 - 0.7-beta1 560 - features: vsprintf, support for named placeholders 561 - enhancements: format cache, reduced global namespace pollution 562 5632010.05.22 - 0.6: 564 - reverted to 0.4 and fixed the bug regarding the sign of the number 0 565 Note: 566 Thanks to Raphael Pigulla <raph (at] n3rd [dot) org> (http://www.n3rd.org/) 567 who warned me about a bug in 0.5, I discovered that the last update was 568 a regress. I appologize for that. 569 5702010.05.09 - 0.5: 571 - bug fix: 0 is now preceeded with a + sign 572 - bug fix: the sign was not at the right position on padded results (Kamal Abdali) 573 - switched from GPL to BSD license 574 5752007.10.21 - 0.4: 576 - unit test and patch (David Baird) 577 5782007.09.17 - 0.3: 579 - bug fix: no longer throws exception on empty paramenters (Hans Pufal) 580 5812007.09.11 - 0.2: 582 - feature: added argument swapping 583 5842007.04.03 - 0.1: 585 - initial release 586**/ 587 588var sprintf = (function() { 589 function get_type(variable) { 590 return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase(); 591 } 592 function str_repeat(input, multiplier) { 593 for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */} 594 return output.join(''); 595 } 596 597 var str_format = function() { 598 if (!str_format.cache.hasOwnProperty(arguments[0])) { 599 str_format.cache[arguments[0]] = str_format.parse(arguments[0]); 600 } 601 return str_format.format.call(null, str_format.cache[arguments[0]], arguments); 602 }; 603 604 // convert object to simple one line string without indentation or 605 // newlines. Note that this implementation does not print array 606 // values to their actual place for sparse arrays. 607 // 608 // For example sparse array like this 609 // l = [] 610 // l[4] = 1 611 // Would be printed as "[1]" instead of "[, , , , 1]" 612 // 613 // If argument 'seen' is not null and array the function will check for 614 // circular object references from argument. 615 str_format.object_stringify = function(obj, depth, maxdepth, seen) { 616 var str = ''; 617 if (obj != null) { 618 switch( typeof(obj) ) { 619 case 'function': 620 return '[Function' + (obj.name ? ': '+obj.name : '') + ']'; 621 break; 622 case 'object': 623 if ( obj instanceof Error) { return '[' + obj.toString() + ']' }; 624 if (depth >= maxdepth) return '[Object]' 625 if (seen) { 626 // add object to seen list 627 seen = seen.slice(0) 628 seen.push(obj); 629 } 630 if (obj.length != null) { //array 631 str += '['; 632 var arr = [] 633 for (var i in obj) { 634 if (seen && seen.indexOf(obj[i]) >= 0) arr.push('[Circular]'); 635 else arr.push(str_format.object_stringify(obj[i], depth+1, maxdepth, seen)); 636 } 637 str += arr.join(', ') + ']'; 638 } else if ('getMonth' in obj) { // date 639 return 'Date(' + obj + ')'; 640 } else { // object 641 str += '{'; 642 var arr = [] 643 for (var k in obj) { 644 if(obj.hasOwnProperty(k)) { 645 if (seen && seen.indexOf(obj[k]) >= 0) arr.push(k + ': [Circular]'); 646 else arr.push(k +': ' +str_format.object_stringify(obj[k], depth+1, maxdepth, seen)); 647 } 648 } 649 str += arr.join(', ') + '}'; 650 } 651 return str; 652 break; 653 case 'string': 654 return '"' + obj + '"'; 655 break 656 } 657 } 658 return '' + obj; 659 } 660 661 str_format.format = function(parse_tree, argv) { 662 var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length; 663 for (i = 0; i < tree_length; i++) {
664 node_type = get_type(parse_tree[i]); 665 if (node_type === 'string') { 666 output.push(parse_tree[i]); 667 } 668 else if (node_type === 'array') { 669 match = parse_tree[i]; // convenience purposes only 670 if (match[2]) { // keyword argument 671 arg = argv[cursor]; 672 for (k = 0; k < match[2].length; k++) { 673 if (!arg.hasOwnProperty(match[2][k])) { 674 throw new Error(sprintf('[sprintf] property "%s" does not exist', match[2][k])); 675 } 676 arg = arg[match[2][k]]; 677 } 678 } 679 else if (match[1]) { // positional argument (explicit) 680 arg = argv[match[1]]; 681 } 682 else { // positional argument (implicit) 683 arg = argv[cursor++]; 684 } 685 686 if (/[^sO]/.test(match[8]) && (get_type(arg) != 'number')) { 687 throw new Error(sprintf('[sprintf] expecting number but found %s "' + arg + '"', get_type(arg))); 688 } 689 switch (match[8]) { 690 case 'b': arg = arg.toString(2); break; 691 case 'c': arg = String.fromCharCode(arg); break; 692 case 'd': arg = parseInt(arg, 10); break; 693 case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break; 694 case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break; 695 case 'O': arg = str_format.object_stringify(arg, 0, parseInt(match[7]) || 5); break; 696 case 'o': arg = arg.toString(8); break; 697 case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break; 698 case 'u': arg = Math.abs(arg); break; 699 case 'x': arg = arg.toString(16); break; 700 case 'X': arg = arg.toString(16).toUpperCase(); break; 701 } 702 arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg); 703 pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' '; 704 pad_length = match[6] - String(arg).length; 705 pad = match[6] ? str_repeat(pad_character, pad_length) : ''; 706 output.push(match[5] ? arg + pad : pad + arg); 707 } 708 } 709 return output.join(''); 710 }; 711 712 str_format.cache = {}; 713 714 str_format.parse = function(fmt) { 715 var _fmt = fmt, match = [], parse_tree = [], arg_names = 0; 716 while (_fmt) { 717 if ((match = /^[^\x25]+/.exec(_fmt)) !== null) { 718 parse_tree.push(match[0]); 719 } 720 else if ((match = /^\x25{2}/.exec(_fmt)) !== null) { 721 parse_tree.push('%'); 722 } 723 else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosOuxX])/.exec(_fmt)) !== null) { 724 if (match[2]) { 725 arg_names |= 1; 726 var field_list = [], replacement_field = match[2], field_match = []; 727 if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { 728 field_list.push(field_match[1]); 729 while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { 730 if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { 731 field_list.push(field_match[1]); 732 } 733 else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) { 734 field_list.push(field_match[1]); 735 } 736 else { 737 throw new Error('[sprintf] ' + replacement_field); 738 } 739 } 740 } 741 else { 742 throw new Error('[sprintf] ' + replacement_field); 743 } 744 match[2] = field_list; 745 } 746 else { 747 arg_names |= 2; 748 } 749 if (arg_names === 3) { 750 throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported'); 751 } 752 parse_tree.push(match); 753 } 754 else { 755 throw new Error('[sprintf] ' + _fmt); 756 } 757 _fmt = _fmt.substring(match[0].length); 758 } 759 return parse_tree; 760 }; 761 762 return str_format; 763})(); 764 765var vsprintf = function(fmt, argv) { 766 var argvClone = argv.slice(); 767 argvClone.unshift(fmt); 768 return sprintf.apply(null, argvClone); 769}; 770 771module.exports = sprintf; 772sprintf.sprintf = sprintf; 773sprintf.vsprintf = vsprintf; 774 775},{}],7:[function(require,module,exports){ 776'use strict'; 777 778Object.defineProperty(exports, "__esModule", { 779 value: true 780}); 781exports.default = { 782 hard_sigmoid: 'float @activation1(float data){\n return clamp(data * 0.2 + 0.5, 0.0, 1.0);\n}', 783 linear: '#define @activation1 \n', 784 relu: 'float @activation1(float data){\n return max(data, 0.0);\n}\n', 785 rgb: 'float @activation1(float data){\n return data / 255.0; \n}', 786 sigmoid: 'float @activation1(float data){\n return (1.0/(1.0 + exp(-2.0 * \n clamp(data,-20.0, 20.0) )));\n}\n', 787 tanh: 'float @activation1(float data){\n float e = exp(2.0 * clamp(data, -20.0, 20.0) );\n return (e-1.0)/(e+1.0);\n}' 788}; 789 790},{}],8:[function(require,module,exports){ 791'use strict'; 792 793Object.defineProperty(exports, "__esModule", { 794 value: true 795}); 796exports.init = init; 797exports.encode = encode; 798exports.decode = decode; 799var encodeShader = exports.encodeShader = 'uniform float @range;\n\nvec4 @encode1(float v) {\n\tfloat z = clamp(v / @range + 0.5, 0.0, 1.0);\n\n\treturn mod(z * vec4(\n\t\t256.0 * 256.0 * 256.0 * 256.0,\n\t\t256.0 * 256.0 * 256.0,\n\t\t256.0 * 256.0,\n\t\t256.0\n\t), vec4(256.0)) / 255.0;\n}'; 800var decodeShader = exports.decodeShader = 'uniform float @range;\n\nfloat @decode1(vec4 rgba) {\n\tfloat f = dot(rgba, vec4(\n\t\t255.0 / 256.0 / 256.0 / 256.0 / 256.0,\n\t\t255.0 / 256.0 / 256.0 / 256.0,\n\t\t255.0 / 256.0 / 256.0,\n\t\t255.0 / 256.0\n\t));\n\treturn (f - 0.5) * @range;\n}'; 801 802function init(shape, format) { 803 return { 804 range: format.range || 4096 805 }; 806} 807 808function encode(buf, value, info) { 809 var z = Math.min(1, Math.max(0, value / info.range + 0.5)); 810 buf[0] = z * 256 * 256 * 256 * 256 % 256; 811 buf[1] = z * 256 * 256 * 256 % 256; 812 buf[2] = z * 256 * 256 % 256; 813 buf[3] = z * 256 % 256; 814} 815 816function decode(buf) { 817 return buf[0] / 256.0 / 256.0 / 256.0 / 256.0 + buf[1] / 256.0 / 256.0 / 256.0 + buf[2] / 256.0 / 256.0 + buf[3] / 256.0; 818} 819 820},{}],9:[function(require,module,exports){ 821'use strict'; 822 823Object.defineProperty(exports, "__esModule", { 824 value: true 825}); 826exports.init = init; 827exports.encode = encode; 828exports.decode = decode; 829var encodeShader = exports.encodeShader = '// https://github.com/mikolalysenko/glsl-read-float/blob/master/index.glsl\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nvec4 @encode1(float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c.abgr / 255.0;\n}\n\n// TODO: compare with http://stackoverflow.com/a/7237286'; 830var decodeShader = exports.decodeShader = '// TODO: compare with http://stackoverflow.com/a/7237286\n\nfloat @decode1(vec4 val){\n vec4 scl = floor(255.0 * val + 0.5);\n float sgn = (scl.a < 128.0) ? 1.0 : -1.0;\n float exn = mod(scl.a * 2.0, 256.0) + floor(scl.b / 128.0) - 127.0;\n float man = 1.0 +\n (scl.r / 8388608.0) + \n (scl.g / 32768.0) +\n mod(scl.b, 128.0) / 128.0;\n return sgn * man * pow(2.0, exn);\n}\n'; 831 832function init(shape, format) { 833 return {}; 834} 835 836var tmp_float = new Float32Array(1), 837 tmp_int = new Uint8Array(tmp_float.buffer); 838 839function encode(buf, value) { 840 tmp_float[0] = value; 841 buf.set(tmp_int, 0); 842} 843 844function decode(buf) { 845 tmp_int.set(buf); 846 return tmp_float[0]; 847} 848 849},{}],10:[function(require,module,exports){ 850'use strict'; 851 852Object.defineProperty(exports, "__esModule", { 853 value: true 854}); 855 856var _index = require('./pack/stride/index.js'); 857 858var pack_stride = _interopRequireWildcard(_index); 859 860var _index2 = require('./pack/tile/index.js'); 861 862var pack_tile = _interopRequireWildcard(_index2); 863 864var _index3 = require('./codec/fixnum/index.js'); 865
866var codec_fixnum = _interopRequireWildcard(_index3); 867 868var _index4 = require('./codec/softfloat/index.js'); 869 870var codec_softfloat = _interopRequireWildcard(_index4); 871 872var _index5 = require('./activation/index.js'); 873 874var _index6 = _interopRequireDefault(_index5); 875 876function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 877 878function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } 879 880exports.default = { 881 pack: { 882 stride: pack_stride, 883 tile: pack_tile 884 }, 885 886 read_shim: 'vec4 @read4(ivec4 pos){\n int z = 4 * (pos.z / 4);\n \n if(@shape.z - z == 1){\n return vec4(\n @read(ivec4(pos.xy, z , pos.w)), \n 0,\n 0,\n 0\n );\n }else if(@shape.z - z == 2){\n return vec4(\n @read(ivec4(pos.xy, z , pos.w)), \n @read(ivec4(pos.xy, z + 1, pos.w)),\n 0,\n 0\n );\n }else if(@shape.z - z == 3){\n return vec4(\n @read(ivec4(pos.xy, z , pos.w)), \n @read(ivec4(pos.xy, z + 1, pos.w)),\n @read(ivec4(pos.xy, z + 2, pos.w)),\n 0\n );\n }\n \n return vec4(\n @read(ivec4(pos.xy, z , pos.w)),\n @read(ivec4(pos.xy, z + 1, pos.w)),\n @read(ivec4(pos.xy, z + 2, pos.w)),\n @read(ivec4(pos.xy, z + 3, pos.w))\n );\n}', 887 write_shim: 'vec4 process4(ivec4 pos);\nfloat process(ivec4 pos){\n return chsel(process4(ivec4(pos.xy, 4 * (pos.z / 4), pos.w)), imod(pos.z, 4));\n}', 888 889 codec: { 890 fixnum: codec_fixnum, 891 softfloat: codec_softfloat 892 }, 893 activations: _index6.default 894}; 895 896},{"./activation/index.js":7,"./codec/fixnum/index.js":8,"./codec/softfloat/index.js":9,"./pack/stride/index.js":11,"./pack/tile/index.js":12}],11:[function(require,module,exports){ 897'use strict'; 898 899Object.defineProperty(exports, "__esModule", { 900 value: true 901}); 902exports.writeShader = exports.readShader = undefined; 903exports.init = init; 904exports.pack = pack; 905exports.unpack = unpack; 906 907var _ndarray = require('ndarray'); 908 909var _ndarray2 = _interopRequireDefault(_ndarray); 910 911function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 912 913var readShader = exports.readShader = 'uniform sampler2D @tex;\nuniform ivec2 @texSize;\nuniform ivec4 @shape;\nuniform vec4 @stride;\n\n\nfloat @read(ivec4 pos){\n\tint tile = int(dot(vec4(pos), @stride));\n\treturn @decode1(texture2D(@tex,\n\t\t(vec2(0.5, 0.5) + vec2(tile2vec(tile, @texSize.x))) \n\t\t/ vec2(@texSize)));\n}'; 914var writeShader = exports.writeShader = 'uniform ivec2 @texSize;\nuniform ivec4 @shape;\nuniform vec4 @stride;\n\n// vec4 clampify(vec4 v){\n// return vec4(ivec4(clamp(v, vec4(0), vec4(1)) * 255.0)) / 255.0;\n// }\n\nfloat process(ivec4 pos);\nvoid main(){\n\tint tile = vec2tile(ivec2(gl_FragCoord.xy), @texSize.x);\n\tint chunks = @shape.x * @shape.y * @shape.z * @shape.w;\n\tif(tile >= chunks){ checkerboard(); return; }\n\n\tgl_FragColor = @encode1(@activation1(process(ivec4(\n\t\timod(tile, @shape.x),\n\t\timod(tile / @shape.x, @shape.y),\n\t\timod(tile / @shape.x / @shape.y, @shape.z ),\n\t\ttile / @shape.x / @shape.y / @shape.z\n\t))));\n}'; 915 916function init(shape) { 917 // var length = 4 * Math.ceil(shape[2] / 4) * shape[3] * shape[1] * shape[0]; 918 // var cols = Math.ceil(Math.sqrt(length) / 4) * 4; 919 920 var length = shape[2] * shape[3] * shape[1] * shape[0]; 921 var cols = Math.ceil(Math.sqrt(length)); 922 var texSize = [cols, Math.ceil(length / cols)]; 923 return { 924 texSize: texSize, 925 shape: shape, 926 // vec4(1, @shape.x, @shape.x * @shape.y, @shape.x * @shape.y * @shape.z) 927 stride: [1, shape[0], shape[0] * shape[1], shape[0] * shape[1] * shape[2]] 928 }; 929} 930 931function pack(info, array, encode1, format) { 932 // return Uint8Array or Float32Array 933 array = (0, _ndarray2.default)(array.data, array.shape.concat([1, 1, 1, 1]).slice(0, 4), array.stride.concat([1, 1, 1, 1]).slice(0, 4), array.offset); 934 935 var shape = info.shape; 936 var length = info.texSize[0] * info.texSize[1] * 4; 937 938 if (format.type === 'float32') { 939 var data = new Float32Array(length); 940 } else if (format.type === 'uint8') { 941 var data = new Uint8Array(length); 942 } 943 944 for (var x = 0; x < shape[0]; x++) { 945 for (var y = 0; y < shape[1]; y++) { 946 for (var z = 0; z < shape[2]; z++) { 947 for (var w = 0; w < shape[3]; w++) { 948 var tile = x + y * shape[0] + z * shape[0] * shape[1] + w * shape[0] * shape[1] * shape[2]; 949
950 encode1(data.subarray(4 * tile, 4 * tile + 4), array.get(x, y, z, w), info); 951 } 952 } 953 } 954 } 955 956 return data; 957} 958 959function unpack(info, data, decode1, type) { 960 if (type != 'float32') throw new Error('not impl'); 961 962 var shape = info.shape; 963 var length = shape.reduce(function (a, b) { 964 return a * b; 965 }); 966 967 var array = (0, _ndarray2.default)(new Float32Array(length), shape.concat([1, 1, 1, 1]).slice(0, 4)); 968 969 for (var x = 0; x < shape[0]; x++) { 970 for (var y = 0; y < shape[1]; y++) { 971 for (var z = 0; z < shape[2]; z++) { 972 for (var w = 0; w < shape[3]; w++) { 973 var tile = x + y * shape[0] + z * shape[0] * shape[1] + w * shape[0] * shape[1] * shape[2]; 974 975 array.set(x, y, z, w, decode1(data.subarray(4 * tile, 4 * tile + 4), info)); 976 } 977 } 978 } 979 } 980 return array; 981} 982 983},{"ndarray":5}],12:[function(require,module,exports){ 984'use strict'; 985 986Object.defineProperty(exports, "__esModule", { 987 value: true 988}); 989exports.writeShader = exports.readShader = undefined; 990exports.init = init; 991exports.pack = pack; 992exports.unpack = unpack; 993 994var _ndarray = require('ndarray'); 995 996var _ndarray2 = _interopRequireDefault(_ndarray); 997 998function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 999 1000var readShader = exports.readShader = 'uniform sampler2D @tex;\nuniform ivec2 @texSize;\nuniform ivec4 @shape;\nuniform int @cols;\n\nfloat @read(ivec4 pos){\n return @decode1(texture2D(@tex, (\n vec2(tile2vec(\n vec2tile(pos.zw, @shape.z)\n , @cols) * ivec2(@shape.xy)) +\n vec2(pos.xy) + vec2(0.5, 0.5)\n ) / vec2(@texSize)));\n}\n'; 1001var writeShader = exports.writeShader = 'uniform ivec2 @texSize;\nuniform ivec4 @shape;\nuniform int @cols;\n\n// vec4 clampify(vec4 v){\n// return vec4(ivec4(clamp(v, vec4(0), vec4(1)) * 255.0)) / 255.0;\n// }\n\nfloat process(ivec4 pos);\nvoid main(){\n int tile = vec2tile(ivec2(gl_FragCoord.xy) / @shape.xy, @cols);\n if(tile >= @shape.z * @shape.w){ checkerboard(); return; }\n\n gl_FragColor = @encode1(@activation1(process(ivec4(\n \timod(gl_FragCoord.x, @shape.x),\n \timod(gl_FragCoord.y, @shape.y),\n // mod(vec2(gl_FragCoord.xy), vec2(@shape.xy)), \n tile2vec(tile, @shape.z)))));\n}'; 1002function init(shape) { 1003 var width = shape[0]; 1004 // we pick the number of columns so we can keep 1005 // the texture as square as possible, with the 1006 // minimal amount of wasted space. 1007 1008 var tiles = shape[2] * shape[3], 1009 cols = Math.max(1, Math.min(tiles, Math.ceil(Math.sqrt(shape[0] * shape[1] * tiles) / width))); 1010 1011 var texSize = [width * cols, shape[1] * Math.ceil(tiles / cols)]; 1012 1013 return { 1014 texSize: texSize, 1015 cols: cols, 1016 shape: shape 1017 }; 1018} 1019 1020function pack(info, ndarray) { 1021 // return Uint8Array or Float32Array 1022 1023 1024 // uniform sampler2D @_tex; 1025 // uniform ivec2 @_texSize; 1026 // uniform ivec4 @_shape; 1027 // uniform int @_cols; 1028 1029 // return { 1030 // tex: 1031 // texSize: 1032 // shape: 1033 // cols: 1034 // } 1035 throw new Error("not implemented: format/1-4/pack/tile/index.js:pack"); 1036} 1037 1038function unpack(info, arr) { 1039 // return ndarray 1040 throw new Error("not implemented: format/1-4/pack/tile/index.js:unpack"); 1041} 1042 1043},{"ndarray":5}],13:[function(require,module,exports){ 1044'use strict'; 1045 1046Object.defineProperty(exports, "__esModule", { 1047 value: true 1048}); 1049exports.default = { 1050 hard_sigmoid: 'vec4 @activation4(vec4 data){\n return clamp(data * vec4(0.2,0.2,0.2,0.2) + \n vec4(.5,.5,.5,.5), vec4(0,0,0,0), vec4(1,1,1,1));\n}', 1051 linear: '#define @activation4 \n', 1052 relu: 'vec4 @activation4(vec4 data){\n return max(data, vec4(0, 0, 0, 0));\n}\n', 1053 rgb: 'vec4 @activation4(vec4 data){\n return data / 255.0; \n}', 1054 sigmoid: 'vec4 @activation4(vec4 data){\n return (vec4(1,1,1,1)/(vec4(1,1,1,1) + exp(-2.0 * \n clamp(data,vec4(-20,-20,-20,-20), vec4(20,20,20,20)) )));\n}\n', 1055 tanh: 'vec4 @activation4(vec4 data){\n vec4 e = exp(2.0 * clamp(data, vec4(-20,-20,-20,-20), vec4(20,20,20,20)) );\n return (e-vec4(1, 1, 1, 1))/(e+vec4(1, 1, 1, 1));\n}' 1056}; 1057 1058},{}],14:[function(require,module,exports){ 1059'use strict'; 1060 1061Object.defineProperty(exports, "__esModule", { 1062 value: true 1063}); 1064exports.init = init; 1065exports.encode = encode; 1066exports.decode = decode; 1067var encodeShader = exports.encodeShader = 'uniform vec2 @range;\n\nvec4 @encode4(vec4 v){\n\treturn (v - vec4(@range.x)) / vec4(@range.y
1067- @range.x);\n}'; 1068var decodeShader = exports.decodeShader = 'uniform vec2 @range;\n\nvec4 @decode4(vec4 v){\n\treturn v * vec4(@range.y - @range.x) + vec4(@range.x);\n}'; 1069 1070function init(shape, format) { 1071 return { 1072 range: [isFinite(format.min) ? format.min : 0, isFinite(format.max) ? format.max : 1] 1073 // max: , 1074 // min: , 1075 }; 1076} 1077 1078function encode(data, r, g, b, a, info) { 1079 1080 data[0] = Math.round(255 * Math.min(1, Math.max(0, (r - info.range[0]) / (info.range[1] - info.range[0])))); 1081 data[1] = Math.round(255 * Math.min(1, Math.max(0, (g - info.range[0]) / (info.range[1] - info.range[0])))); 1082 data[2] = Math.round(255 * Math.min(1, Math.max(0, (b - info.range[0]) / (info.range[1] - info.range[0])))); 1083 data[3] = Math.round(255 * Math.min(1, Math.max(0, (a - info.range[0]) / (info.range[1] - info.range[0])))); 1084 // console.log(data[0], data[1], data[2]) 1085} 1086 1087function decode(data, r, g, b, a, info) { 1088 data[0] = r / 255 * (info.range[1] - info.range[0]) + info.range[0]; 1089 data[1] = g / 255 * (info.range[1] - info.range[0]) + info.range[0]; 1090 data[2] = b / 255 * (info.range[1] - info.range[0]) + info.range[0]; 1091 data[3] = a / 255 * (info.range[1] - info.range[0]) + info.range[0]; 1092} 1093 1094},{}],15:[function(require,module,exports){ 1095'use strict'; 1096 1097Object.defineProperty(exports, "__esModule", { 1098 value: true 1099}); 1100exports.init = init; 1101exports.encode = encode; 1102exports.decode = decode; 1103var encodeShader = exports.encodeShader = '#define @encode4 \n '; 1104var decodeShader = exports.decodeShader = '#define @decode4 \n'; 1105 1106function init(shape, format) { 1107 return {}; 1108} 1109 1110function encode(data, r, g, b, a) { 1111 data[0] = r; 1112 data[1] = g; 1113 data[2] = b; 1114 data[3] = a; 1115} 1116 1117function decode(data, r, g, b, a) { 1118 data[0] = r; 1119 data[1] = g; 1120 data[2] = b; 1121 data[3] = a; 1122} 1123 1124},{}],16:[function(require,module,exports){ 1125'use strict'; 1126 1127Object.defineProperty(exports, "__esModule", { 1128 value: true 1129}); 1130 1131var _index = require('./pack/stride/index.js'); 1132 1133var pack_stride = _interopRequireWildcard(_index); 1134 1135var _index2 = require('./pack/tile/index.js'); 1136 1137var pack_tile = _interopRequireWildcard(_index2); 1138 1139var _index3 = require('./codec/raw/index.js'); 1140 1141var codec_raw = _interopRequireWildcard(_index3); 1142 1143var _index4 = require('./codec/linquant/index.js'); 1144 1145var codec_linquant = _interopRequireWildcard(_index4); 1146 1147var _index5 = require('./activation/index.js'); 1148 1149var _index6 = _interopRequireDefault(_index5); 1150 1151function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 1152 1153function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } 1154 1155exports.default = { 1156 pack: { 1157 stride: pack_stride, 1158 tile: pack_tile 1159 }, 1160 1161 read_shim: 'float @read(ivec4 pos){\n return chsel(@read4(pos), imod(pos.z, 4));\n}\n', 1162 write_shim: 'float process(ivec4 pos);
1162\nvec4 process4(ivec4 pos){\n int z = 4 * (pos.z / 4);\n\n if(@shape.z - z == 1){\n return vec4(\n process(ivec4(pos.xy, z , pos.w)), \n 0,\n 0,\n 0\n );\n }else if(@shape.z - z == 2){\n return vec4(\n process(ivec4(pos.xy, z , pos.w)), \n process(ivec4(pos.xy, z + 1, pos.w)),\n 0,\n 0\n );\n }else if(@shape.z - z == 3){\n return vec4(\n process(ivec4(pos.xy, z , pos.w)), \n process(ivec4(pos.xy, z + 1, pos.w)),\n process(ivec4(pos.xy, z + 2, pos.w)),\n 0\n );\n }\n \n return vec4(\n process(ivec4(pos.xy, z , pos.w)),\n process(ivec4(pos.xy, z + 1, pos.w)),\n process(ivec4(pos.xy, z + 2, pos.w)),\n process(ivec4(pos.xy, z + 3, pos.w))\n );\n}', 1163 1164 codec: { 1165 raw: codec_raw, 1166 linquant: codec_linquant 1167 }, 1168 activations: _index6.default 1169}; 1170 1171},{"./activation/index.js":13,"./codec/linquant/index.js":14,"./codec/raw/index.js":15,"./pack/stride/index.js":17,"./pack/tile/index.js":18}],17:[function(require,module,exports){ 1172'use strict'; 1173 1174Object.defineProperty(exports, "__esModule", { 1175 value: true 1176}); 1177exports.writeShader = exports.readShader = undefined; 1178 1179var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); 1180 1181exports.init = init; 1182exports.pack = pack; 1183exports.unpack = unpack; 1184 1185var _ndarray = require('ndarray'); 1186 1187var _ndarray2 = _interopRequireDefault(_ndarray); 1188 1189function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 1190 1191var readShader = exports.readShader = 'uniform sampler2D @tex;\nuniform ivec2 @texSize;\nuniform ivec4 @shape;\nuniform vec4 @stride;\n\n\nvec4 @read4(ivec4 pos){\n\tint tile = int(dot(vec4(pos), @stride));\n\treturn @decode4(texture2D(@tex,\n\t\t(vec2(0.5, 0.5) + vec2(tile2vec(tile, @texSize.x))) \n\t\t/ vec2(@texSize)));\n}'; 1192var writeShader = exports.writeShader = 'uniform ivec2 @texSize;\nuniform ivec4 @shape;\nuniform vec4 @stride;\n\nvec4 process4(ivec4 pos);\nvoid main(){\n\tint tile = @texSize.x * int(gl_FragCoord.y) + int(gl_FragCoord.x);\n\tint shapez = ceildiv(@shape.z, 4);\n\tif(tile >= int(@stride.w) * @shape.w){ checkerboard(); return; }\n\n\tgl_FragColor = @encode4(@activation4(process4(ivec4(\n\t\timod(tile, @shape.x),\n\t\timod(tile / @shape.x, @shape.y),\n\t\t4 * imod(tile / @shape.x / @shape.y, shapez),\n\t\ttile / @shape.x / @shape.y / shapez\n\t))));\n}\n'; 1193function init(shape) { 1194 var length = Math.ceil(shape[2] / 4) * shape[3] * shape[1] * shape[0]; 1195 var cols = Math.ceil(Math.sqrt(length)); 1196 var texSize = [cols, Math.ceil(length / cols)]; 1197 1198 console.assert(texSize[0] * texSize[1] >= length); 1199 return { 1200 texSize: texSize, 1201 shape: shape, 1202 1203 stride: [1, shape[0], shape[0] * shape[1] / 4, // the /4 is because of the color channel 1204 shape[0] * shape[1] * Math.ceil(shape[2] / 4)] 1205 }; 1206} 1207 1208function pack(info, array, encode4, format) { 1209 // return Uint8Array or Float32Array 1210 1211 array = (0, _ndarray2.default)(array.data, array.shape.concat([1, 1, 1, 1]).slice(0, 4), array.stride.concat([1, 1, 1, 1]).slice(0, 4), array.offset); 1212 1213 var _info$texSize = _slicedToArray(info.texSize, 2), 1214 width = _info$texSize[0], 1215 height = _info$texSize[1], 1216 length = width * height * 4; 1217 1218 var shape = info.shape; 1219 1220 if (format.type === 'float32') { 1221 var data = new Float32Array(length); 1222 } else if (format.type === 'uint8') { 1223 var data = new Uint8Array(length); 1224 } 1225 1226 var chans = Math.ceil(info.shape[2] / 4); 1227 1228 for (var i = 0; i < info.shape[0]; i++) { 1229 for (var j = 0; j < info.shape[1]; j++) { 1230 for (var k = 0; k < chans; k++) { 1231 var b = Math.min(k * 4 + 4, shape[2]) - k * 4; 1232 for (var w = 0; w < info.shape[3]; w++) { 1233 1234 var tile = i + j * shape[0] + k * shape[0] * shape[1] + w * shape[0] * shape[1] * chans; 1235 1236 var pos = 4 * tile; 1237 encode4(data.subarray(pos, pos + 4), b < 1 ? 0 : array.get(i, j, 4 * k + 0, w), b < 2 ? 0 : array.get(i, j, 4 * k + 1, w), b < 3 ? 0 : array.get(i, j, 4 * k + 2, w), b < 4 ? 0 : array.get(i, j, 4 * k + 3, w), info); 1238 } 1239 } 1240 } 1241 } 1242 1243 return data; 1244} 1245 1246function unpack(info, data, decode4, type) { 1247 1248 var shape = info.shape; 1249 var shapelength = shape.reduce(function (a, b) { 1250 return a * b; 1251 }); 1252 1253 var _info$texSize2 = _slicedToArray(info.texSize, 2), 1254 width = _info$texSize2[0], 1255 height = _info$texSize2[1], 1256 length = width * height * 4; 1257 1258 var chans = Math.ceil(info.shape[2] / 4); 1259 1260 // if(type === 'float32'){ 1261 var array = (0, _ndarray2.default)(new Float32Array(shapelength), shape); 1262 var buf = new Float32Array(4); 1263 // }else if(type == 'uint8'){ 1264 // var array = ndarray(new Uint8Array(shapelength), shape) 1265 // var buf = new Uint8Array(4); 1266 // }else throw new Error('unimplemented type'); 1267 1268 1269 for (var i = 0; i < info.shape[0]; i++) { 1270 for (var j = 0; j < info.shape[1]; j++) { 1271 for (var k = 0; k < chans; k++) { 1272 var b = Math.min(k * 4 + 4, shape[2]) - k * 4; 1273 for (var w = 0; w < info.shape[3]; w++) { 1274 1275 var tile = i + j * shape[0] + k * shape[0] * shape[1] + w * shape[0] * shape[1] * chans; 1276 1277 decode4(buf, data[4 * tile + 0], data[4 * tile + 1], data[4 * tile + 2], data[4 * tile + 3], info); 1278 1279 for (var x = 0; x < b; x++) { 1280 array.set(i, j, 4 * k + x, w, buf[x]); 1281 } 1282 } 1283 } 1284 } 1285 } 1286 1287 return array; 1288} 1289 1290},{"ndarray":5}],18:[function(require,module,exports){ 1291'use strict'; 1292 1293Object.defineProperty(exports, "__esModule", { 1294 value: true 1295}); 1296exports.writeShader = exports.readShader = undefined; 1297 1298var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); }
1298 else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); 1299 1300exports.init = init; 1301exports.pack = pack; 1302exports.unpack = unpack; 1303 1304var _ndarray = require('ndarray'); 1305 1306var _ndarray2 = _interopRequireDefault(_ndarray); 1307 1308function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 1309 1310var readShader = exports.readShader = 'uniform sampler2D @tex;\nuniform ivec2 @texSize;\nuniform ivec4 @shape;\nuniform int @cols;\n\n\nvec4 @read4(ivec4 pos){\n\tfloat tile = float(vec2tile(pos.zw / ivec2(4, 1), ceildiv(@shape.z, 4)));\n return @decode4(texture2D(@tex, (\n vec2(\n \tmod(tile, float(@cols)),\n \tfloor(tile / float(@cols))\n ) * vec2(@shape.xy) +\n vec2(pos.xy) + vec2(0.5, 0.5)\n ) / vec2(@texSize)));\n}\n'; 1311var writeShader = exports.writeShader = 'uniform ivec2 @texSize;\nuniform ivec4 @shape;\nuniform int @cols;\n\nvec4 process4(ivec4 pos);\nvoid main(){\n int tile = vec2tile(ivec2(gl_FragCoord.xy) / @shape.xy, @cols);\n int chunks = ceildiv(@shape.z, 4);\n if(tile * 4 >= @shape.z * @shape.w){ checkerboard(); return; }\n gl_FragColor = @encode4(@activation4(process4(ivec4(\n mod(gl_FragCoord.xy, vec2(@shape.xy)), \n tile2vec(tile, chunks) * ivec2(4, 1)))));\n}\n\n'; 1312 1313function init(shape) { 1314 var width = shape[0]; // var width = shape[0] * 4; 1315 // we pick the number of columns so we can keep 1316 // the texture as square as possible, with the 1317 // minimal amount of wasted space. 1318 1319 var tiles = Math.ceil(shape[2] / 4) * shape[3], 1320 cols = Math.max(1, Math.min(tiles, Math.round(Math.sqrt(shape[0] * shape[1] * tiles) / width))); 1321 1322 var texSize = [width * cols, shape[1] * Math.ceil(tiles / cols)]; 1323 1324 return { 1325 texSize: texSize, 1326 cols: cols, 1327 shape: shape 1328 }; 1329} 1330 1331function pack(info, array, encode4, format) { 1332 array = (0, _ndarray2.default)(array.data, array.shape.concat([1, 1, 1, 1]).slice(0, 4), array.stride.concat([1, 1, 1, 1]).slice(0, 4), array.offset); 1333 1334 var shape = array.shape, 1335 tiles = Math.ceil(shape[2] / 4) * shape[3], 1336 tw = shape[0], 1337 th = shape[1], 1338 cols = info.cols, 1339 _info$texSize = _slicedToArray(info.texSize, 2), 1340 width = _info$texSize[0], 1341 height = _info$texSize[1], 1342 chunks = Math.ceil(shape[2] / 4), 1343 length = width * height * 4; 1344 1345 1346 if (format.type === 'float32') { 1347 var data = new Float32Array(length); 1348 } else if (format.type === 'uint8') { 1349 var data = new Uint8Array(length); 1350 } 1351 1352 for (var z = 0; z < chunks; z++) { 1353 for (var w = 0; w < shape[3]; w++) { 1354 var tile = w * chunks + z; 1355 var b = Math.min(z * 4 + 4, shape[2]) - z * 4; 1356 1357 var ih = th * Math.floor(tile / cols); 1358 var jw = tw * (tile % cols); 1359 1360 for (var i = 0; i < tw; i++) { 1361 for (var j = 0; j < th; j++) { 1362 1363 var pos = 4 * ((ih + j) * width + jw + i); 1364 encode4(data.subarray(pos, pos + 4), b < 1 ? 0 : array.get(i, j, 4 * z + 0, w), b < 2 ? 0 : array.get(i, j, 4 * z + 1, w), b < 3 ? 0 : array.get(i, j, 4 * z + 2, w), b < 4 ? 0 : array.get(i, j, 4 * z + 3, w), info); 1365 } 1366 } 1367 } 1368 } 1369 return data; 1370} 1371 1372function unpack(info, data, decode4, type) { 1373 throw new Error("not implemented: format/4-4/pack/tile/index.js:unpack"); 1374} 1375 1376},{"ndarray":5}],19:[function(require,module,exports){ 1377'use strict'; 1378 1379Object.defineProperty(exports, "__esModule", { 1380 value: true 1381}); 1382 1383var _index = require('./4-4/index.js'); 1384 1385var _index2 = _interopRequireDefault(_index); 1386 1387var _index3 = require('./1-4/index.js'); 1388 1389var _index4 = _interopRequireDefault(_index3); 1390 1391function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 1392 1393exports.default = { 1394 '4:4': _index2.default, 1395 '1:4': _index4.default 1396}; 1397 1398},{"./1-4/index.js":10,"./4-4/index.js":16}],20:[function(require,module,exports){ 1399'use strict'; 1400 1401Object.defineProperty(exports, "__esModule", { 1402 value: true 1403}); 1404 1405var _index = require('./tensor/index.js'); 1406 1407Object.defineProperty(exports, 'Tensor', { 1408 enumerable: true, 1409 get: function get() { 1410 return _index.Tensor; 1411 } 1412}); 1413Object.defineProperty(exports, 'OutputTensor', { 1414 enumerable: true, 1415 get: function get() { 1416 return _index.OutputTensor; 1417 } 1418}); 1419Object.defineProperty(exports, 'InPlaceTensor', { 1420 enumerable: true, 1421 get: function get() { 1422 return _index.InPlaceTensor; 1423 } 1424}); 1425 1426var _index2 = require('./runtime/index.js'); 1427 1428Object.defineProperty(exports, 'Run', { 1429 enumerable: true, 1430 get: function get() { 1431 return _index2.Run; 1432 } 1433}); 1434Object.defineProperty(exports, 'Compile', { 1435 enumerable: true, 1436 get: function get() { 1437 return _index2.Compile; 1438 } 1439}); 1440 1441var _util = require('./util.js'); 1442 1443Object.defineProperty(exports, 'createGL', { 1444 enumerable: true, 1445 get: function get() { 1446 return _util.createGL; 1447 } 1448}); 1449 1450},{"./runtime/index.js":23,"./tensor/index.js":30,"./util.js":32}],21:[function(require,module,exports){ 1451'use strict'; 1452 1453Object.defineProperty(exports, "__esModule", { 1454 value: true 1455}); 1456exports.checkLinkError = checkLinkError;
1457exports.checkShaderError = checkShaderError; 1458exports.checkFramebufferError = checkFramebufferError; 1459// code for pretty printing shader errors from regl 1460 1461function checkLinkError(gl, program, fragShader, vertShader, command) { 1462 if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { 1463 var errLog = gl.getProgramInfoLog(program); 1464 var fragParse = parseSource(fragShader, command); 1465 var vertParse = parseSource(vertShader, command); 1466 1467 var header = 'Error linking program with vertex shader, "' + vertParse[0].name + '", and fragment shader "' + fragParse[0].name + '"'; 1468 1469 if (typeof document !== 'undefined') { 1470 console.log('%c' + header + '\n%c' + errLog, 'color:red;text-decoration:underline;font-weight:bold', 'color:red'); 1471 } else { 1472 console.log(header + '\n' + errLog); 1473 } 1474 1475 console.log(fragShader); 1476 1477 throw new Error(header); 1478 } 1479} 1480 1481function checkShaderError(gl, shader, source, type, command) { 1482 if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { 1483 var errLog = gl.getShaderInfoLog(shader); 1484 var typeName = type === gl.FRAGMENT_SHADER ? 'fragment' : 'vertex'; 1485 // checkCommandType(source, 'string', typeName + ' shader source must be a string', command) 1486 1487 var files = parseSource(source, command); 1488 var errors = parseErrorLog(errLog); 1489 annotateFiles(files, errors); 1490 1491 Object.keys(files).forEach(function (fileNumber) { 1492 var file = files[fileNumber]; 1493 if (!file.hasErrors) { 1494 return; 1495 } 1496 1497 var strings = ['']; 1498 var styles = ['']; 1499 1500 function push(str, style) { 1501 strings.push(str); 1502 styles.push(style || ''); 1503 } 1504 1505 push('file number ' + fileNumber + ': ' + file.name + '\n', 'color:red;text-decoration:underline;font-weight:bold'); 1506 1507 file.lines.forEach(function (line) { 1508 if (line.errors.length > 0) { 1509 push(leftPad(line.number, 4) + '| ', 'background-color:yellow; font-weight:bold'); 1510 push(line.line + '\n', 'color:red; background-color:yellow; font-weight:bold'); 1511 1512 // try to guess token 1513 var offset = 0; 1514 line.errors.forEach(function (error) { 1515 var message = error.message; 1516 var token = /^\s*\'(.*)\'\s*\:\s*(.*)$/.exec(message); 1517 if (token) { 1518 var tokenPat = token[1]; 1519 message = token[2]; 1520 switch (tokenPat) { 1521 case 'assign': 1522 tokenPat = '='; 1523 break; 1524 } 1525 offset = Math.max(line.line.indexOf(tokenPat, offset), 0); 1526 } else { 1527 offset = 0; 1528 } 1529 1530 push(leftPad('| ', 6)); 1531 push(leftPad('^^^', offset + 3) + '\n', 'font-weight:bold'); 1532 push(leftPad('| ', 6)); 1533 push(message + '\n', 'font-weight:bold'); 1534 }); 1535 push(leftPad('| ', 6) + '\n'); 1536 } else { 1537 push(leftPad(line.number, 4) + '| '); 1538 push(line.line + '\n', 'color:red'); 1539 } 1540 }); 1541 if (typeof document !== 'undefined') { 1542 styles[0] = strings.join('%c'); 1543 console.log.apply(console, styles); 1544 } else { 1545 console.log(strings.join('')); 1546 } 1547 }); 1548 1549 throw new Error('Error compiling ' + typeName + ' shader, ' + files[0].name); 1550 } 1551} 1552 1553function checkFramebufferError(gl) { 1554 1555 var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); 1556 if (status != gl.FRAMEBUFFER_COMPLETE) { 1557 var statusCode = {}; 1558 statusCode[gl.FRAMEBUFFER_COMPLETE] = 'complete'; 1559 statusCode[gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT] = 'incomplete attachment'; 1560 statusCode[gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS] = 'incomplete dimensions'; 1561 statusCode[gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT] = 'incomplete, missing attachment'; 1562 statusCode[gl.FRAMEBUFFER_UNSUPPORTED] = 'unsupported'; 1563 throw new Error('framebuffer configuration not supported, status = ' + statusCode[status]); 1564 } 1565} 1566 1567function leftPad(str, n) { 1568 str = str + ''; 1569 while (str.length < n) { 1570 str = ' ' + str; 1571 } 1572 return str; 1573} 1574 1575function ShaderFile() { 1576 this.name = 'unknown'; 1577 this.lines = []; 1578 this.index = {}; 1579 this.hasErrors = false;
1580} 1581 1582function ShaderLine(number, line) { 1583 this.number = number; 1584 this.line = line; 1585 this.errors = []; 1586} 1587 1588function ShaderError(fileNumber, lineNumber, message) { 1589 this.file = fileNumber; 1590 this.line = lineNumber; 1591 this.message = message; 1592} 1593 1594function parseSource(source, command) { 1595 var lines = source.split('\n'); 1596 var lineNumber = 1; 1597 var fileNumber = 0; 1598 var files = { 1599 unknown: new ShaderFile(), 1600 0: new ShaderFile() 1601 }; 1602 files.unknown.name = files[0].name = 'unknown'; 1603 files.unknown.lines.push(new ShaderLine(0, '')); 1604 for (var i = 0; i < lines.length; ++i) { 1605 var line = lines[i]; 1606 var parts = /^\s*\#\s*(\w+)\s+(.+)\s*$/.exec(line); 1607 if (parts) { 1608 switch (parts[1]) { 1609 case 'line': 1610 var lineNumberInfo = /(\d+)(\s+\d+)?/.exec(parts[2]); 1611 if (lineNumberInfo) { 1612 lineNumber = lineNumberInfo[1] | 0; 1613 if (lineNumberInfo[2]) { 1614 fileNumber = lineNumberInfo[2] | 0; 1615 if (!(fileNumber in files)) { 1616 files[fileNumber] = new ShaderFile(); 1617 } 1618 } 1619 } 1620 break; 1621 case 'define': 1622 var nameInfo = /SHADER_NAME(_B64)?\s+(.*)$/.exec(parts[2]); 1623 if (nameInfo) { 1624 files[fileNumber].name = nameInfo[1] ? decodeB64(nameInfo[2]) : nameInfo[2]; 1625 } 1626 break; 1627 } 1628 } 1629 files[fileNumber].lines.push(new ShaderLine(lineNumber++, line)); 1630 } 1631 Object.keys(files).forEach(function (fileNumber) { 1632 var file = files[fileNumber]; 1633 file.lines.forEach(function (line) { 1634 file.index[line.number] = line; 1635 }); 1636 }); 1637 return files; 1638} 1639 1640function parseErrorLog(errLog) { 1641 var result = []; 1642 errLog.split('\n').forEach(function (errMsg) { 1643 if (errMsg.length < 5) { 1644 return; 1645 } 1646 var parts = /^ERROR\:\s+(\d+)\:(\d+)\:\s*(.*)$/.exec(errMsg); 1647 if (parts) { 1648 result.push(new ShaderError(parts[1] | 0, parts[2] | 0, parts[3].trim())); 1649 } else if (errMsg.length > 0) { 1650 result.push(new ShaderError('unknown', 0, errMsg)); 1651 } 1652 }); 1653 return result; 1654} 1655 1656function annotateFiles(files, errors) { 1657 errors.forEach(function (error) { 1658 var file = files[error.file]; 1659 if (file) { 1660 var line = file.index[error.line]; 1661 if (line) { 1662 line.errors.push(error); 1663 file.hasErrors = true; 1664 return; 1665 } 1666 } 1667 files.unknown.hasErrors = true; 1668 files.unknown.lines[0].errors.push(error); 1669 }); 1670} 1671 1672},{}],22:[function(require,module,exports){ 1673'use strict'; 1674 1675Object.defineProperty(exports, "__esModule", { 1676 value: true 1677}); 1678exports.default = assembleFragmentShader; 1679 1680var _base = require('../tensor/base.js'); 1681 1682var _base2 = _interopRequireDefault(_base); 1683 1684function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 1685 1686var TENSOR_FRAGMENT_HEADER = 'precision highp int;\nprecision highp float;\n\nint imod(int f, int p){ return f - p * (f / p); }\nint vec2tile(ivec2 v, int rows){ return rows * v.y + v.x; }\nivec2 tile2vec(int f, int rows){ return ivec2(imod(f, rows), f / rows); }\nint ceildiv(int a, int b){ return (a - 1) / b + 1; }\nvoid checkerboard(){ gl_FragColor = vec4(mod(gl_FragCoord.x - gl_FragCoord.y, 2.0), 0.2, 0.1, 1); }\n\nfloat chsel(vec4 val, int ch){\n\tif(ch == 0) return val.r;\n\tif(ch == 1) return val.g;\n\tif(ch == 2) return val.b;\n\treturn val.a;\n}\n'; // import { Tensor, OutputTensor, InPlaceTensor } from '../tensor/index.js' 1687function assembleFragmentShader(shaderGen, output, uniforms) { 1688 var tensorShader = shaderGen(uniforms, output); 1689 1690 var fragmentShader = TENSOR_FRAGMENT_HEADER; 1691 for (var uniform in uniforms) { 1692 if (uniforms[uniform] instanceof _base2.default) { 1693 var tensor = uniforms[uniform]; 1694 1695 fragmentShader += tensor._format.codec.decodeShader.replace(/@/g, uniform + '_') + '\n'; 1696 fragmentShader += tensor._format.pack.readShader.replace(/@/g, uniform + '_') + '\n'; 1697 1698 if (tensor.format.density == '1:4' && new RegExp(uniform + '_read4\\b').test(tensorShader) || tensor.format.density == '4:4' && new RegExp(uniform + '_read\\b').test(tensorShader)) { 1699 fragmentShader += tensor._format.read_shim.replace(/@/g, uniform + '_') + '\n'; 1700 } 1701 } 1702 } 1703 1704 var activation = typeof uniforms._activation == 'string' && uniforms._activation != 'linear' ? uniforms._activation.toLowerCase() : 'linear'; 1705 1706 if (!(activation in output._format.activations)) throw new Error('Unknown activation type ' + activation); 1707 1708 fragmentShader += output._format.activations[activation].replace(/@/g, 'out_') + '\n'; 1709 fragmentShader += output._format.codec.encodeShader.replace(/@/g, 'out_') + '\n'; 1710 fragmentShader += output._format.pack.writeShader.replace(/@/g, 'out_') + '\n'; 1711 1712 if (output.format.density == '1:4' && /process4\b/.test(tensorShader) || output.format.density == '4:4' && /process\b/.test(tensorShader)) { 1713 fragmentShader += output._format.write_shim.replace(/@/g, 'out_') + '\n'; 1714 } 1715 1716 fragmentShader += tensorShader.replace(/@/g, 'out_'); 1717 1718 // console.log(fragmentShader) 1719 1720 return fragmentShader; 1721} 1722 1723},{"../tensor/base.js":27}],23:[function(require,module,exports){ 1724'use strict'; 1725 1726Object.defineProperty(exports, "__esModule", { 1727 value: true 1728}); 1729exports.Compile = Compile; 1730exports.Run = Run; 1731 1732var _program = require('./program.js'); 1733 1734var _program2 = _interopRequireDefault(_program); 1735 1736var _frag = require('./frag.js'); 1737 1738var _frag2 = _interopRequireDefault(_frag); 1739 1740var _index = require('../tensor/index.js'); 1741 1742var _check = require('./check.js'); 1743 1744var _tnsl = require('./tnsl.js'); 1745
1746var _tnsl2 = _interopRequireDefault(_tnsl); 1747 1748var _timer = require('./timer.js'); 1749 1750function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 1751 1752function Compile(shaderGen, output) { 1753 var uniforms = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; 1754 1755 var startTime = (0, _timer.now)(); 1756 if (!(output instanceof _index.OutputTensor)) throw new Error("First argument must be an instance of OutputTensor"); 1757 1758 if (typeof shaderGen === 'string') shaderGen = (0, _tnsl2.default)(shaderGen); 1759 1760 var gl = output.gl; 1761 var program = (0, _program2.default)(gl, (0, _frag2.default)(shaderGen, output, uniforms)); 1762 var compileTime = (0, _timer.now)() - startTime; 1763 // console.log('Compile Time', compileTime) 1764 return program; 1765} 1766 1767function Run(shaderGen, output) { 1768 var uniforms = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; 1769 var callback = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; 1770 1771 var tp = Compile(shaderGen, output, uniforms); 1772 1773 var gl = output.gl; 1774 1775 if (callback && typeof callback != 'function') throw new Error('Callback must be a function'); 1776 if (callback) { 1777 (0, _timer.beginTimer)(gl, { 1778 shader: shaderGen, 1779 output: output 1780 }); 1781 } 1782 1783 gl.useProgram(tp.program); 1784 gl.disable(gl.DEPTH_TEST); 1785 gl.disable(gl.BLEND); 1786 1787 var setUniform = tp.setUniform, 1788 texIndex = 0, 1789 mustSwap = false; 1790 1791 for (var name in uniforms) { 1792 if (name.startsWith('_')) continue; 1793 1794 if (name + '_tex' in tp.uniformTypes) { 1795 var tensor = uniforms[name]; 1796 if (tensor.gl !== output.gl) throw new Error('Uniforms must belong to same GL context as output'); 1797 if (tensor === output) mustSwap = true; 1798 1799 for (var uniform in tensor.info) { 1800 setUniform(name + '_' + uniform, tensor.info[uniform]); 1801 } 1802 1803 gl.activeTexture(gl['TEXTURE' + texIndex]); 1804 gl.bindTexture(gl.TEXTURE_2D, tensor.tex); 1805 setUniform(name + '_tex', texIndex); 1806 1807 texIndex++; 1808 } else if (name in tp.uniformTypes) { 1809 setUniform(name, uniforms[name]); 1810 } else { 1811 throw new Error("Unknown uniform " + name); 1812 } 1813 } 1814 1815 // Ordinarily we can't write to the same texture that we're using as 1816 // an input, as this could lead to all sorts of terrible race conditions, 1817 // undefined behavior, and invalid state. InPlaceTensors actually consist 1818 // of a pair of textures which are swapped for these in-place operations. 1819 if (mustSwap) output.swap(); 1820 1821 for (var _uniform in output.info) { 1822 setUniform('out_' + _uniform, output.info[_uniform]); 1823 } 1824 1825 gl.bindFramebuffer(gl.FRAMEBUFFER, output.fbo); 1826 gl.viewport(0, 0, output.info.texSize[0], output.info.texSize[1]); 1827 gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); // draw to framebuffer 1828 1829 (0, _check.checkFramebufferError)(gl); 1830 1831 // var runTime = now() - startTime; 1832 // timer.end() 1833 if (callback) { 1834 (0, _timer.endTimer)(gl, function (info) { 1835 // console.log('GPU time: ', info) 1836 callback(info); 1837 }); 1838 } 1839 // console.log('CPU Run Time', runTime) 1840 1841 return output; 1842} 1843 1844},{"../tensor/index.js":30,"./check.js":21,"./frag.js":22,"./program.js":24,"./timer.js":25,"./tnsl.js":26}],24:[function(require,module,exports){ 1845'use strict'; 1846 1847Object.defineProperty(exports, "__esModule", { 1848 value: true 1849}); 1850exports.default = getTensorProgram; 1851exports.bindAttributeBuffer = bindAttributeBuffer; 1852exports.createShaderProgram = createShaderProgram; 1853 1854var _check = require('./check.js'); 1855 1856var TENSOR_VERTEX_SHADER = '\n precision highp float;\n attribute vec2 a_position;\n void main() {\n gl_Position = vec4(a_position, 0, 1);\n }\n'; 1857 1858var UNIFORM_SETTERS = { vec4: '4fv', vec3: '3fv', vec2: '2fv', float: '1f',
1859 ivec4: '4iv', ivec3: '3iv', ivec2: '2iv', int: '1i', 1860 sampler2D: '1i' }; 1861 1862function getTensorProgram(gl, fragmentShader) { 1863 if (!gl._tensorPrograms) gl._tensorPrograms = {}; 1864 if (fragmentShader in gl._tensorPrograms) { 1865 return gl._tensorPrograms[fragmentShader]; 1866 } 1867 var program = createTensorProgram(gl, fragmentShader); 1868 gl._tensorPrograms[fragmentShader] = program; 1869 return program; 1870} 1871 1872function createTensorProgram(gl, fragmentShader) { 1873 var program = createShaderProgram(gl, TENSOR_VERTEX_SHADER, fragmentShader); 1874 1875 gl.useProgram(program); 1876 bindAttributeBuffer(gl, program); 1877 1878 var uniformTypes = extractUniformDeclarations(fragmentShader), 1879 uniformLocs = {}; 1880 1881 function addUniform(name, type) { 1882 uniformLocs[name] = { loc: gl.getUniformLocation(program, name), type: type }; 1883 } 1884 1885 for (var name in uniformTypes) { 1886 var type = uniformTypes[name]; 1887 if (type in UNIFORM_SETTERS) { 1888 addUniform(name, type); 1889 } else throw new Error("Unknown uniform type " + type); 1890 } 1891 1892 function setUniform(name, value) { 1893 if (!(name in uniformLocs)) { 1894 throw new Error("Could not find uniform " + name); 1895 } 1896 gl['uniform' + UNIFORM_SETTERS[uniformLocs[name].type]](uniformLocs[name].loc, value); 1897 } 1898 1899 return { 1900 program: program, 1901 uniformLocs: uniformLocs, 1902 uniformTypes: uniformTypes, 1903 setUniform: setUniform 1904 }; 1905} 1906 1907function bindAttributeBuffer(gl, program) { 1908 gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); 1909 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW); 1910 1911 var positionLocation = gl.getAttribLocation(program, "a_position"); 1912 gl.enableVertexAttribArray(positionLocation); 1913 gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0); 1914} 1915 1916function extractUniformDeclarations(str) { 1917 var uniforms = {}; 1918 str = str.replace(/((?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:\/\/.*))/g, ''); 1919 str = str.replace(/\/\/.*\n/g, ''); 1920 var m, 1921 re = /uniform\s*([\w_]+)\s*([\w_]+)/g; 1922 while (m = re.exec(str)) { 1923 uniforms[m[2]] = m[1]; 1924 }return uniforms; 1925} 1926 1927function createShaderProgram(gl, vertexSource, fragmentSource) { 1928 var vertexShader = compileShader(gl, vertexSource, gl.VERTEX_SHADER); 1929 var fragmentShader = compileShader(gl, fragmentSource, gl.FRAGMENT_SHADER); 1930 1931 // var debug = gl.getExtension('WEBGL_debug_shaders') 1932 // console.log(debug.getTranslatedShaderSource(vertexShader)); 1933 // console.log(debug.getTranslatedShaderSource(fragmentShader)); 1934 1935 var program = gl.createProgram(); 1936 gl.attachShader(program, vertexShader); 1937 gl.attachShader(program, fragmentShader); 1938 gl.linkProgram(program); 1939 1940 // interestingly enough it seems like Safari never emits 1941 // a shader program link error. 1942 (0, _check.checkLinkError)(gl, program, fragmentSource, vertexSource); 1943 1944 return program; 1945} 1946 1947function compileShader(gl, shaderSource, shaderType) { 1948 var shader = gl.createShader(shaderType); 1949 gl.shaderSource(shader, shaderSource); 1950 gl.compileShader(shader); 1951 var success = gl.getShaderParameter(shader, gl.COMPILE_STATUS); 1952 (0, _check.checkShaderError)(gl, shader, shaderSource, shaderType); 1953 return shader; 1954} 1955 1956},{"./check.js":21}],25:[function(require,module,exports){ 1957'use strict'; 1958 1959Object.defineProperty(exports, "__esModule", { 1960 value: true 1961}); 1962exports.now = now; 1963exports.beginTimer = beginTimer; 1964exports.endTimer = endTimer; 1965function now() { 1966 if (typeof performance === 'undefined') { 1967 return Date.now(); 1968 } else { 1969 return performance.now(); 1970 } 1971} 1972 1973function getTimer(gl) { 1974 if (gl.NO_PROFILE) return; 1975 if (typeof gl.TIMER_POOL === 'undefined') { 1976 var extTimer = gl.getExtension('ext_disjoint_timer_query'); 1977 if (!extTimer || !extTimer.createQueryEXT) { 1978 gl.NO_PROFILE = true; 1979 return; 1980 } 1981 gl.TIMER_POOL = createTimer(gl); 1982 } 1983 return gl.TIMER_POOL; 1984} 1985 1986function beginTimer(gl) { 1987 var info = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 1988 1989 var timer = getTimer(gl); 1990 if (timer) { 1991 timer.begin(info); 1992 } 1993} 1994 1995function endTimer(gl, callback) { 1996 var timer = getTimer(gl); 1997 if (timer) { 1998 timer.end(callback); 1999 } else if (callback) { 2000 console.warn("Can not trigger callback: implementation does not support ext_disjoint_timer_query"); 2001 } 2002} 2003 2004function createTimer(gl) { 2005 var extTimer = gl.getExtension('ext_disjoint_timer_query'); 2006 2007 var queryPool = [];
2008 function allocQuery() { 2009 return queryPool.pop() || extTimer.createQueryEXT(); 2010 } 2011 function freeQuery(query) { 2012 queryPool.push(query); 2013 } 2014 2015 var pendingQueries = []; 2016 function beginQuery(info) { 2017 var query = allocQuery(); 2018 extTimer.beginQueryEXT(extTimer.TIME_ELAPSED_EXT, query); 2019 pendingQueries.push([query, info]); 2020 } 2021 2022 function endQuery() { 2023 extTimer.endQueryEXT(extTimer.TIME_ELAPSED_EXT); 2024 } 2025 2026 function callback(info, time) { 2027 var fn = info.callback; 2028 info.gpuTime = time; 2029 delete info.callback; 2030 if (fn) fn(info); 2031 } 2032 2033 function monitorPending() { 2034 for (var i = 0; i < pendingQueries.length; ++i) { 2035 var query = pendingQueries[i][0]; 2036 if (extTimer.getQueryObjectEXT(query, extTimer.QUERY_RESULT_AVAILABLE_EXT)) { 2037 var queryTime = extTimer.getQueryObjectEXT(query, extTimer.QUERY_RESULT_EXT); 2038 callback(pendingQueries[i][1], queryTime / 1e6); 2039 freeQuery(query); 2040 pendingQueries.splice(i, 1); 2041 i--; 2042 } 2043 } 2044 } 2045 2046 var isPolling = false; 2047 function loop() { 2048 if (pendingQueries.length > 0) { 2049 monitorPending(); 2050 requestAnimationFrame(loop); 2051 } else { 2052 isPolling = false; 2053 } 2054 } 2055 2056 var currentInfo = null; 2057 return { 2058 begin: function begin() { 2059 var info = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 2060 2061 if (currentInfo) throw new Error('beginTimer was called before previous endTimer'); 2062 currentInfo = info; 2063 info.cpuStartTime = now(); 2064 beginQuery(currentInfo); 2065 }, 2066 end: function end(fn) {
2067 currentInfo.cpuTime = now() - currentInfo.cpuStartTime; 2068 delete currentInfo.cpuStartTime; 2069 currentInfo.callback = fn; 2070 currentInfo = null; 2071 endQuery(); 2072 2073 if (isPolling === false) { 2074 isPolling = true; 2075 requestAnimationFrame(loop); 2076 } 2077 } 2078 }; 2079} 2080 2081},{}],26:[function(require,module,exports){ 2082'use strict'; 2083 2084Object.defineProperty(exports, "__esModule", { 2085 value: true 2086}); 2087exports.default = TNSL; 2088// TNSL (pronounced tinsel) 2089// is a domain specific language based on GLSL 2090// for helping with the writing code that 2091// computes with tensors. 2092 2093// A limitation of GLSL is that the condition 2094// of any loop has to be statically known 2095// (e.g. counters up to a fixed constant 2096// value) which is problematic if we want 2097// to write general code that depends on 2098// the size of the input tensors 2099 2100// TNSL adds the following syntax: 2101// #(image.shape) 2102// which will be replaced with an ivec4 2103// containing the shape of the input tensor "image" 2104// automatically 2105 2106function TNSL(str) { 2107 if (typeof str != 'string') throw new Error('TNSL shader preprocessor only accepts strings'); 2108 2109 return function (uniforms, output) { 2110 return str 2111 // comment out the tensor struct definitions 2112 .replace(/uniform\s*Tensor\s*([\w_]+)\s*;/g, '/* (Tensor $1) */') 2113 2114 // this is the macro syntax 2115 .replace(/\#\(([\w\.\s]+)\)/g, function (all, body) { 2116 var obj = uniforms; 2117 var _iteratorNormalCompletion = true; 2118 var _didIteratorError = false; 2119 var _iteratorError = undefined; 2120 2121 try { 2122 for (var _iterator = body.split('.')[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { 2123 var part = _step.value; 2124 2125 obj = obj[part.trim()]; 2126 } 2127 } catch (err) { 2128 _didIteratorError = true; 2129 _iteratorError = err; 2130 } finally { 2131 try { 2132 if (!_iteratorNormalCompletion && _iterator.return) { 2133 _iterator.return(); 2134 } 2135 } finally { 2136 if (_didIteratorError) { 2137 throw _iteratorError; 2138 } 2139 } 2140 } 2141 2142 if (typeof obj == 'number') { 2143 return obj.toString(); 2144 } else if (Array.isArray(obj) && obj.length <= 4 && obj.length > 1) { 2145 return (obj.every(Number.isInteger) ? 'i' : '') + 'vec' + obj.length + '(' + obj.join(',') + ')'; 2146 } 2147 throw new Error('Can not inline expression ' + body); 2148 }) 2149 // tensor.read4(x, 0) => tensor.read4(ivec4(x, 0, 0, 0)) 2150 // this transformation takes place when there are 2 or more arguments 2151 // as otherwise it's not possible to statically determine whether x is 2152 // of type ivec4 or a number 2153 .replace(/\b(\w+)\s*\.\s*(read4?)\b\s*\(([^\(\)]+)\)/g, function (all, name, prop, arg) { 2154 if (name in uniforms && uniforms[name].shape) { 2155 var parts = arg.split(','), 2156 padded = parts.concat(['0', '0', '0', '0'].slice(0, 4 - parts.length)); 2157 if (parts.length < 2 || parts.length > 4) return all; 2158 var vec = 'ivec4(' + padded.join(',') + ')'; 2159 return name + '_' + prop + '(' + vec + ')'; 2160 } 2161 return all; 2162 }) 2163 2164 // tensor.shape => tensor_shape 2165 .replace(/\b(\w+)\s*\.\s*(\w+)\b/g, function (all, name, prop) { 2166 if (name in uniforms && uniforms[name].shape) { 2167 return name + '_' + prop; 2168 } 2169 return all; 2170 }); 2171 // .replace(/\#\s*(\w+)\s*\[(.*?)\]/g, function(all, tensor, body){ 2172 // return tensor + '_read(ivec4(' + body + '))' 2173 // }) 2174 }; 2175} 2176 2177},{}],27:[function(require,module,exports){ 2178'use strict'; 2179 2180Object.defineProperty(exports, "__esModule", { 2181 value: true 2182}); 2183 2184var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); 2185 2186var _helpers = require('./helpers.js'); 2187 2188var _index = require('../format/index.js'); 2189 2190var _index2 = _interopRequireDefault(_index); 2191 2192function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 2193 2194function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 2195 2196// The tensor format is a JSON object that specifies how 2197// the tensor is represented as a texture 2198// it consists of several keys: 2199 2200// type: uint8 | float32 2201// density: 4:4 | 1:4 2202// pack: stride | tile 2203// codec: 2204// softfloat | fixnum (1:4) 2205// raw | linquant (4:4) 2206 2207var BaseTensor = function () { 2208 function BaseTensor() { 2209 _classCallCheck(this, BaseTensor); 2210 } 2211 2212 _createClass(BaseTensor, [{ 2213 key: '_init', 2214 2215 // we arent using a constructor because we want to be able to run 2216 // this instanceof OutputTensor from within the Tensor constructor 2217 2218 value: function _init(gl, format, shape, data) { 2219 // validate glcontext 2220 if (!gl.createTexture) throw new Error('Invalid WebGLRenderingContext'); 2221 this.gl = gl; 2222 2223 // validate shape 2224 if (!Array.isArray(shape)) throw new Error("shape must be Array"); 2225 if (shape.length > 4) throw new Error("Tensor must have dimension <= 4"); 2226 if (shape.some(function (k) { 2227 return !isFinite(k) || k < 1 || !Number.isInteger(k); 2228 })) throw new Error('Invalid shape: ' + shape); 2229 shape = shape.concat([1, 1, 1, 1]).slice(0, 4); 2230 this.shape = shape; 2231 2232 // validate format 2233 if (!['float32', 'uint8'].includes(format.type)) throw new Error('format.type must be uint8 or float32'); 2234 if (format.density in _index2.default) { 2235 var fd = _index2.default[format.density]; 2236 if (!(format.pack in fd.pack)) throw new Error('format.pack must be ' + Object.keys(fd.pack).join(' or ')); 2237 if (!(format.codec in fd.codec)) throw new Error('format.codec must be ' + Object.keys(fd.codec).join(' or ')); 2238 } else throw new Error('format.density must be ' + Object.keys(_index2.default).join(' or ')); 2239 2240 this.format = format; 2241 2242 // calculate texture size 2243 this.info = Object.assign({}, this._format.pack.init(shape, format), this._format.codec.init(shape, format)); 2244 if (!this.info.texSize) throw new Error('Format did n
2244ot yield texSize'); 2245 2246 // initialize texture 2247 this.tex = (0, _helpers.makeTexture)(gl); 2248 this.update(data); 2249 } 2250 }, { 2251 key: '_update', 2252 value: function _update(data) { 2253 if (data !== null) { 2254 if (this.format.type === 'uint8') { 2255 if (Array.isArray(data) || data instanceof Uint8ClampedArray) data = new Uint8Array(data); 2256 if (!(data instanceof Uint8Array)) throw new Error('data must be Uint8Array'); 2257 } else if (this.format.type === 'float32') { 2258 if (Array.isArray(data) || data instanceof Float64Array) data = new Float32Array(data); 2259 if (!(data instanceof Float32Array)) throw new Error('data must be Float32Array'); 2260 } else throw new Error('Type must be uint8 or float32'); 2261 if (data.length !== this.info.texSize[0] * this.info.texSize[1] * 4) throw new Error('data is the wrong length'); 2262 } 2263 // if(data) console.log('_update', data); 2264 var gl = this.gl; 2265 gl.bindTexture(gl.TEXTURE_2D, this.tex); 2266 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.info.texSize[0], this.info.texSize[1], 0, gl.RGBA, this.format.type == 'uint8' ? gl.UNSIGNED_BYTE : gl.FLOAT, data); 2267 } 2268 }, { 2269 key: 'update', 2270 value: function update(data) { 2271 if (!data) return this._update(null); 2272 if (data.shape) return this._update(this._format.pack.pack(this.info, data, this._format.codec.encode, this.format)); 2273 if (this.type != 'uint8') console.warn('Calling update with raw TypedArray may not work across all browsers.'); 2274 return this._update(data); 2275 } 2276 }, { 2277 key: 'destroy', 2278 value: function destroy() { 2279 this.gl.deleteTexture(this.tex); 2280 } 2281 }, { 2282 key: '_format', 2283 get: function get() { 2284 return { 2285 pack: _index2.default[this.format.density].pack[this.format.pack], 2286 codec: _index2.default[this.format.density].codec[this.format.codec], 2287 activations: _index2.default[this.format.density].activations, 2288 read_shim: _index2.default[this.format.density].read_shim, 2289 write_shim: _index2.default[this.format.density].write_shim 2290 }; 2291 } 2292 }]); 2293 2294 return BaseTensor; 2295}(); 2296 2297exports.default = BaseTensor; 2298 2299},{"../format/index.js":19,"./helpers.js":29}],28:[function(require,module,exports){ 2300'use strict'; 2301 2302Object.defineProperty(exports, "__esModule", { 2303 value: true 2304}); 2305exports.default = runFeatureTests; 2306exports.testRenderFloat = testRenderFloat; 2307 2308var _program = require('../runtime/program.js'); 2309 2310var _helpers = require('./helpers.js'); 2311 2312function runFeatureTests(gl) { 2313 2314 if (!gl.FLOAT_TEXTURES_TESTED && !gl.NO_FLOAT_TEXTURES) { 2315 if (!gl.getExtension('OES_texture_float')) { 2316 console.info("This browser does not seem to support OES_texture_float. " + "Using float codec workaround from now on."); 2317 gl.NO_FLOAT_TEXTURES = true; 2318 } 2319 gl.FLOAT_TEXTURES_TESTED = true; 2320 } 2321 2322 if (!gl.NO_FLOAT_TEXTURES) { 2323 if (!gl.RENDER_FLOAT_TESTED && !gl.NO_RENDER_FLOAT) { 2324 if (!testRenderFloat(gl)) { 2325 console.info("This browser supports OES_texture_float, " + "but can not render to floating textures. " + "Using float codec workaround for output tensors from now on."); 2326 gl.NO_RENDER_FLOAT = true; 2327 } 2328 gl.RENDER_FLOAT_TESTED = true; 2329 } 2330 2331 if (!gl.READ_FLOAT_TESTED && !gl.NO_READ_FLOAT && !gl.NO_READ_FLOAT) { 2332 if (!testReadFloat(gl)) { 2333 console.info("This browser supports OES_texture_float, " + "can render to floating point textures, but can not " + "read into a Float32Array buffer. Using float codec " + "workaround for reading from output tensors from now on."); 2334 gl.NO_READ_FLOAT = true; 2335 } 2336 gl.READ_FLOAT_TESTED = true; 2337 } 2338 } 2339} 2340 2341var CHECK_FLOAT_VERTEX = '\n attribute vec2 a_position;\n void main() {\n gl_Position = vec4(a_position, 0, 1);\n }\n'; 2342var CHECK_FLOAT_FRAGMENT = '\n void main() {\n gl_FragColor = vec4(3.14159, -2.71828, 1.61828, 42);\n }\n'; 2343 2344// some browsers (e.g. mobile safari) are capable of initializing floating 2345// point textures but unable to write to them. The only way of finding this 2346// out is by trying to render to a floating point texture and noticing 2347// the invalid framebuffer status. 2348 2349function testRenderFloat(gl) { 2350 var tex = (0, _helpers.makeTexture)(gl); 2351 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 10, 10, 0, gl.RGBA, gl.FLOAT, null); 2352 var fbo = (0, _helpers.makeFrameBuffer)(gl, tex); 2353 2354 var program = (0, _program.createShaderProgram)(gl, CHECK_FLOAT_VERTEX, CHECK_FLOAT_FRAGMENT); 2355 gl.useProgram(program); 2356 (0, _program.bindAttributeBuffer)(gl, program); 2357 2358 gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); 2359 gl.viewport(0, 0, 10, 10); 2360 gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); 2361 2362 var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); 2363 gl.deleteTexture(tex); 2364 gl.deleteFramebuffer(fbo); 2365 gl.deleteProgram(program); 2366 2367 return status == gl.FRAMEBUFFER_COMPLETE; 2368} 2369 2370function testReadFloat(gl) { 2371 var tex = (0, _helpers.makeTexture)(gl); 2372 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 10, 10, 0, gl.RGBA, gl.FLOAT, null); 2373 var fbo = (0, _helpers.makeFrameBuffer)(gl, tex); 2374 2375 var program = (0, _program.createShaderProgram)(gl, CHECK_FLOAT_VERTEX, CHECK_FLOAT_FRAGMENT); 2376 gl.useProgram(program); 2377 (0, _program.bindAttributeBuffer)(gl, program); 2378 2379 gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); 2380 gl.viewport(0, 0, 10, 10); 2381 gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); 2382 2383 var size = [3, 3]; 2384 var pixels = pixels = new Float32Array(size[0] * size[1] * 4); 2385 gl.readPixels(0, 0, size[0], size[1], gl.RGBA, gl.FLOAT, pixels); 2386 2387 gl.deleteTexture(tex); 2388 gl.deleteFramebuffer(fbo); 2389 gl.deleteProgram(program); 2390 2391 var total_error = Math.abs(pixels[0] - 3.14159) + Math.abs(pixels[1] + 2.71828) + Math.abs(pixels[2] - 1.61828) + Math.abs(pixels[3] - 42); 2392 2393 return total_error < 0.01; 2394} 2395 2396},{"../runtime/program.js":24,"./helpers.js":29}],29:[function(require,module,exports){ 2397"use strict"; 2398 2399Object.defineProperty(exports, "__esModule", { 2400 value: true 2401}); 2402exports.makeFrameBuffer = makeFrameBuffer; 2403exports.makeTexture = makeTexture; 2404function makeFrameBuffer(gl, texture) { 2405 var framebuffer = gl.createFramebuffer(); 2406 gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); 2407 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); 2408 return framebuffer; 2409} 2410 2411function makeTexture(gl) { 2412 var texture = gl.createTexture(); 2413 gl.bindTexture(gl.TEXTURE_2D, texture); 2414 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); 2415 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); 2416 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); 2417 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); 2418 2419 return texture; 2420} 2421 2422},{}],30:[function(require,module,exports){ 2423'use strict'; 2424 2425Object.defineProperty(exports, "__esModule", { 2426 value: true 2427}); 2428exports.InPlaceTensor = exports.OutputTensor = exports.Tensor = undefined; 2429 2430var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; 2431 2432var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; 2433 2434var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); 2435 2436var _base = require('./base.js'); 2437 2438var _base2 = _interopRequireDefault(_base); 2439 2440var _show2 = require('./show.js'); 2441 2442var _show3 = _interopRequireDefault(_show2); 2443 2444var _feature = require('./feature.js'); 2445 2446var _feature2 = _interopRequireDefault(_feature); 2447 2448var _helpers = require('./helpers.js'); 2449 2450var _index = require('../runtime/index.js'); 2451 2452var _ndarrayShow = require('ndarray-show'); 2453 2454var _ndarrayShow2 = _interopRequireDefault(_ndarrayShow); 2455 2456var _ndarray = require('ndarray'); 2457 2458var _ndarray2 = _interopRequireDefault(_ndarray); 2459 2460function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 2461 2462function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 2463 2464function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } 2465 2466function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { c
2466onstructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } 2467 2468var Tensor = exports.Tensor = function (_BaseTensor) { 2469 _inherits(Tensor, _BaseTensor); 2470 2471 // new Tensor(gl) 2472 // new Tensor(gl, [1, 1]) 2473 // new Tensor(gl, [1, 1], null) 2474 // new Tensor(gl, [1, 1], data) 2475 // new Tensor(gl, [1, 1], data, { type, pack, codec, density }) 2476 // new Tensor(gl, [1, 1], { type, pack, codec, density }) 2477 // new Tensor(gl, [1, 1], 'softfloat') 2478 // new Tensor(gl, [1, 1], 'float32') 2479 // new Tensor(gl, [1, 1], 'uint8') 2480 // new Tensor(gl, { shape, data }) 2481 // new Tensor(gl, { width, height, data }) 2482 // pix = new Tensor(gl, [1, 1, 4], [1, 0.4, 3, 4], 'uint8') 2483 2484 function Tensor(gl) { 2485 var shape = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; 2486 var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; 2487 var format = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; 2488 2489 _classCallCheck(this, Tensor); 2490 2491 var _this = _possibleConstructorReturn(this, (Tensor.__proto__ || Object.getPrototypeOf(Tensor)).call(this)); 2492 2493 (0, _feature2.default)(gl); 2494 2495 var xdata = data; 2496 if (shape.shape) { 2497 // ndarrays 2498 format = data; 2499 xdata = shape.data; 2500 data = shape; 2501 shape = shape.shape; 2502 } 2503 2504 if (shape.width && shape.height && shape.data) { 2505 // imagedata 2506 data = shape.data; 2507 shape = [shape.width, shape.height]; 2508 } 2509 2510 if (typeof data === 'string') { 2511 // data = uint8 | float32 2512 if (format !== null) throw new Error('Format must not be specified if data is a string.'); 2513 format = data; 2514 data = null; 2515 } else if (data && (typeof data === 'undefined' ? 'undefined' : _typeof(data)) === 'object' && data.type && data.codec && data.pack && data.density) { 2516 if (format !== null) throw new Error('Format must not be specified if data is an object.'); 2517 format = data; 2518 data = null; 2519 } 2520 2521 if (format === null) { 2522 // auto-infer format based on data 2523 if (data === null) { 2524 format = 'float32'; 2525 } else if (xdata instanceof Uint8Array || xdata instanceof Uint8ClampedArray) { 2526 format = 'uint8'; 2527 } else if (xdata instanceof Float32Array || xdata instanceof Float64Array || Array.isArray(xdata)) { 2528 format = 'float32'; 2529 } else throw new Error("Invalid format for data: must be Uint8Array or Float32Array or ndarray"); 2530 } 2531 2532 var type = null; 2533 if (format === 'float32' && (gl.NO_FLOAT_TEXTURES || gl.NO_RENDER_FLOAT && _this instanceof OutputTensor) || format === 'softfloat') { 2534 format = { type: 'uint8', pack: 'stride', density: '1:4', codec: 'softfloat' }; 2535 type = 'float32'; 2536 } else if (format === 'uint8' || format === 'float32') { 2537 format = { type: format, pack: 'stride', density: '4:4', codec: 'raw' }; 2538 } 2539 2540 _this.type = type || format.type; 2541 _this._init(gl, format, shape, data); 2542 return _this; 2543 } 2544 2545 _createClass(Tensor, [{ 2546 key: 'copy', 2547 value: function copy() { 2548 var format = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.type; 2549 var T = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : OutputTensor; 2550 2551 var TENSOR_IDENTITY = '\n uniform Tensor image;\n vec4 process4(ivec4 pos) { return image.read4(pos); }\n '; 2552 var out = new T(this.gl, this.shape, format); 2553 out.run(TENSOR_IDENTITY, { image: this }); 2554 return out; 2555 } 2556 }, { 2557 key: 'withCopy', 2558 value: function withCopy(fn) { 2559 for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { 2560 args[_key - 1] = arguments[_key]; 2561 } 2562 2563 var copy = this.copy.apply(this, args); 2564 var result = fn(copy); 2565 copy.destroy(); 2566 return result; 2567 } 2568 }, {
2569 key: '_show', 2570 value: function _show() { 2571 var opt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 2572 (0, _show3.default)(this.gl, this.tex, opt); 2573 } 2574 }, { 2575 key: 'show', 2576 value: function show() { 2577 var opt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 2578 2579 var gl = this.gl; 2580 if (this.format.pack == 'tile' && this.format.density == '4:4' && this.format.codec == 'raw') { 2581 this._show(opt); 2582 } else { 2583 // C.info.main_input.output.copy({ type: 'uint8', pack: 'tile', density: '4:4', codec: 'linquant', min: 0, max: 255 })._show({ }) 2584 this.withCopy(function (x) { 2585 return x.show(opt); 2586 }, { type: gl.NO_FLOAT_TEXTURES || gl.NO_RENDER_FLOAT ? 'uint8' : 'float32', 2587 pack: 'tile', density: '4:4', codec: 'raw' }); 2588 }; 2589 } 2590 }, { 2591 key: 'run', 2592 value: function run(shader, params) { 2593 throw new Error('Only OutputTensor can run shaders.'); 2594 } 2595 }, { 2596 key: 'compile', 2597 value: function compile(shader, params) { 2598 throw new Error('Only OutputTensor can compile shaders.'); 2599 } 2600 }, { 2601 key: 'read', 2602 value: function read() { 2603 console.warn("Copying before read..."); 2604 return this.withCopy(function (x) { 2605 return x.read(); 2606 }); 2607 } 2608 }, { 2609 key: 'print', 2610 value: function print() { 2611 return (0, _ndarrayShow2.default)(this.read()); 2612 } 2613 }, { 2614 key: 'swap', 2615 value: function swap() { 2616 throw new Error("Only InPlaceTensor can be both a parameter and destination."); 2617 } 2618 }]); 2619 2620 return Tensor; 2621}(_base2.default); 2622 2623var OutputTensor = exports.OutputTensor = function (_Tensor) { 2624 _inherits(OutputTensor, _Tensor); 2625 2626 function OutputTensor() { 2627 var _ref; 2628 2629 _classCallCheck(this, OutputTensor); 2630 2631 for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { 2632 args[_key2] = arguments[_key2]; 2633 } 2634 2635 var _this2 = _possibleConstructorReturn(this, (_ref = OutputTensor.__proto__ || Object.getPrototypeOf(OutputTensor)).call.apply(_ref, [this].concat(args))); 2636 2637 _this2.fbo = (0, _helpers.makeFrameBuffer)(_this2.gl, _this2.tex); 2638 return _this2; 2639 } 2640 2641 _createClass(OutputTensor, [{ 2642 key: 'destroy', 2643 value: function destroy() { 2644 _get(OutputTensor.prototype.__proto__ || Object.getPrototypeOf(OutputTensor.prototype), 'destroy', this).call(this); 2645 this.gl.deleteFramebuffer(this.fbo); 2646 } 2647 }, { 2648 key: '_read', 2649 value: function _read() { 2650 var gl = this.gl, 2651 size = this.info.texSize; 2652 2653 if (this.format.type == 'uint8') { 2654 var glType = gl.UNSIGNED_BYTE, 2655 pixels = new Uint8Array(size[0] * size[1] * 4); 2656 } else if (this.format.type === 'float32') { 2657 var glType = gl.FLOAT, 2658 pixels = new Float32Array(size[0] * size[1] * 4); 2659 } 2660 2661 gl.bindFramebuffer(gl.FRAMEBUFFER, this.fbo); 2662 gl.readPixels(0, 0, size[0], size[1], gl.RGBA, glType, pixels); 2663 2664 // console.log('___read', pixels) 2665 return pixels; 2666 } 2667 }, { 2668 key: 'run', 2669 value: function run(shader, params, callback) { 2670 return (0, _index.Run)(shader, this, params, callback); 2671 } 2672 }, { 2673 key: 'compile', 2674 value: function compile(shader, params) { 2675 return (0, _index.Compile)(shader, this, params); 2676 } 2677 }, { 2678 key: 'read', 2679 value: function read() { 2680 if (this.format.type === 'float32' && this.gl.NO_READ_FLOAT) { 2681 return this.withCopy(function (x) { 2682 return x.read(); 2683 }, 'softfloat'); 2684 } 2685 2686 var array = this._format.pack.unpack(this.info, this._read(), this._format.codec.decode, this.type); 2687 2688 // strip trailing singleton dimensions 2689 var shape = array.shape.slice(0),
2690 stride = array.stride.slice(0); 2691 while (shape[shape.length - 1] == 1 && shape.length > 1) { 2692 shape.pop(); 2693 stride.pop(); 2694 } 2695 return (0, _ndarray2.default)(array.data, shape, stride, array.offset); 2696 } 2697 }]); 2698 2699 return OutputTensor; 2700}(Tensor); 2701 2702var InPlaceTensor = exports.InPlaceTensor = function (_OutputTensor) { 2703 _inherits(InPlaceTensor, _OutputTensor); 2704 2705 function InPlaceTensor() { 2706 var _ref2; 2707 2708 _classCallCheck(this, InPlaceTensor); 2709 2710 for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { 2711 args[_key3] = arguments[_key3]; 2712 } 2713 2714 var _this3 = _possibleConstructorReturn(this, (_ref2 = InPlaceTensor.__proto__ || Object.getPrototypeOf(InPlaceTensor)).call.apply(_ref2, [this].concat(args))); 2715 2716 _this3.tex2 = _this3.tex; 2717 _this3.tex = (0, _helpers.makeTexture)(_this3.gl); 2718 _this3.update(null); 2719 _this3.swap(); 2720 return _this3; 2721 } 2722 2723 _createClass(InPlaceTensor, [{ 2724 key: 'destroy', 2725 value: function destroy() { 2726 _get(InPlaceTensor.prototype.__proto__ || Object.getPrototypeOf(InPlaceTensor.prototype), 'destroy', this).call(this); 2727 this.gl.deleteTexture(this.tex2); 2728 } 2729 }, { 2730 key: 'swap', 2731 value: function swap() { 2732 var tmp = this.tex; 2733 this.tex = this.tex2; 2734 this.tex2 = tmp; 2735 2736 // TODO: investigate performance of using multiple FBOs instead 2737 // of rebinding the framebuffer 2738 var gl = this.gl; 2739 gl.bindFramebuffer(gl.FRAMEBUFFER, this.fbo); 2740 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.tex, 0); 2741 } 2742 }]); 2743 2744 return InPlaceTensor; 2745}(OutputTensor); 2746 2747},{"../runtime/index.js":23,"./base.js":27,"./feature.js":28,"./helpers.js":29,"./show.js":31,"ndarray":5,"ndarray-show":4}],31:[function(require,module,exports){ 2748'use strict'; 2749 2750Object.defineProperty(exports, "__esModule", { 2751 value: true 2752}); 2753exports.default = showTexture; 2754 2755var _program = require('../runtime/program.js'); 2756 2757var SHOW_TEXTURE_VERTEX = '\n attribute vec2 a_position;\n varying mediump vec2 pos;\n void main() {\n pos = (a_position + vec2(1, 1)) / 2.0;\n gl_Position = vec4(a_position, 0, 1);\n }\n'; 2758 2759var SHOW_TEXTURE_FRAGMENT = '\n precision mediump float;\n\n uniform sampler2D tex;\n uniform float scale;\n uniform float offset;\n uniform bool transpose;\n uniform bool flipX;\n uniform bool flipY;\n uniform int channels;\n\n varying vec2 pos;\n\n vec4 colormap(float x) {\n float r = clamp(8.0 / 3.0 * x, 0.0, 1.0);\n float g = clamp(8.0 / 3.0 * x - 1.0, 0.0, 1.0);\n float b = clamp(4.0 * x - 3.0, 0.0, 1.0);\n return vec4(r, g, b, 1.0);\n }\n\n void main() {\n vec2 p = pos;\n if(flipX) p.x = 1.0 - p.x;\n if(flipY) p.y = 1.0 - p.y;\n if(transpose) p = p.yx;\n if(channels == 4){\n gl_FragColor = vec4(vec4(offset, offset, offset, offset) \n + scale * texture2D(tex, p));\n }else if(channels == 3){\n gl_FragColor = vec4(vec3(offset, offset, offset) \n + scale * texture2D(tex, p).rgb, 1);\n }else if(channels == 2){\n gl_FragColor = vec4(vec2(offset, offset) \n + scale * texture2D(tex, p).rg, 0, 1);\n }else if(channels == 1){\n gl_FragColor = colormap(offset + scale * texture2D(tex, p).r);\n }\n }\n'; 2760 2761function showTexture(gl, tex) { 2762 var opt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; 2763 2764 if (!gl._showProgram) { 2765 gl._showProgram = (0, _program.createShaderProgram)(gl, SHOW_TEXTURE_VERTEX, SHOW_TEXTURE_FRAGMENT); 2766 gl.useProgram(gl._showProgram); 2767 (0, _program.bindAttributeBuffer)(gl, gl._showProgram); 2768 gl.uniform1i(gl.getUniformLocation(gl._showProgram, 'tex'), 0); 2769 } 2770 2771 if (gl.canvas && gl.canvas._tfAuto) { 2772 gl.canvas.style.display = 'block'; 2773 gl.canvas.style.position = 'absolute'; 2774 gl.canvas.style.top = 0; 2775 gl.canvas.style.left = 0; 2776 gl.canvas.style.width = Math.min(innerHeight, innerWidth) + 'px'; 2777 gl.canvas.style.height = Math.min(innerHeight, innerWidth) + 'px'; 2778 } 2779 2780 gl.useProgram(gl._showProgram); 2781 gl.activeTexture(gl.TEXTURE0); 2782 gl.bindTexture(gl.TEXTURE_2D, tex); 2783 gl.uniform1f(gl.getUniformLocation(gl._showProgram, 'scale'), opt.scale || 1); 2784 gl.uniform1f(gl.getUniformLocation(gl._showProgram, 'offset'), opt.offset || 0); 2785 gl.uniform1i(gl.getUniformLocation(gl._showProgram, 'transpose'), opt.transpose ? 1 : 0); 2786 gl.uniform1i(gl.getUniformLocation(gl._showProgram, 'flipX'), opt.flipX ? 1 : 0); 2787 gl.uniform1i(gl.getUniformLocation(gl._showProgram, 'flipY'), opt.flipY ? 1 : 0); 2788 gl.uniform1i(gl.getUniformLocation(gl._showProgram, 'channels'), opt.channels || 3); 2789 2790 gl.bindFramebuffer(gl.FRAMEBUFFER, null); 2791 gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); 2792 gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); 2793} 2794 2795},{"../runtime/program.js":24}],32:[function(require,module,exports){ 2796'use strict'; 2797 2798Object.defineProperty(exports, "__esModule", { 2799 value: true 2800}); 2801exports.createGL = createGL; 2802function createGL(canvas) { 2803 if (!canvas) { 2804 canvas = document.createElement('canvas'); 2805 canvas.width = 512; 2806 canvas.height = 512; 2807 canvas.style.display = 'none'; 2808 canvas._tfAuto = true; 2809 document.body.appendChild(canvas); 2810 } 2811 var gl = canvas.getContext("webgl", { antialias: false }) || canvas.getContext("experimental-webgl", { antialias: false });
2812 if (!gl) alert('Could not initialize WebGL, try another browser'); 2813 return gl; 2814} 2815 2816},{}]},{},[20])(20) 2817});
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.