PageRenderTime 37ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/js/src/metrics/jint/v8/raytrace.js

http://github.com/zpao/v8monkey
JavaScript | 3418 lines | 2898 code | 418 blank | 102 comment | 442 complexity | 0f810b31b03b524a557516351b02ad43 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, AGPL-1.0, LGPL-2.1, BSD-3-Clause, GPL-2.0, JSON, Apache-2.0, 0BSD
  1. // The ray tracer code in this file is written by Adam Burmister. It
  2. // is available in its original form from:
  3. //
  4. // http://labs.flog.nz.co/raytracer/
  5. //
  6. // It has been modified slightly by Google to work as a standalone
  7. // benchmark, but the all the computational code remains
  8. // untouched. This file also contains a copy of the Prototype
  9. // JavaScript framework which is used by the ray tracer.
  10. var RayTrace = new BenchmarkSuite('RayTrace', 932666, [
  11. new Benchmark('RayTrace', renderScene)
  12. ]);
  13. // Create dummy objects if we're not running in a browser.
  14. if (typeof document == 'undefined') {
  15. document = { };
  16. window = { opera: null };
  17. navigator = { userAgent: null, appVersion: "" };
  18. }
  19. // ------------------------------------------------------------------------
  20. // ------------------------------------------------------------------------
  21. /* Prototype JavaScript framework, version 1.5.0
  22. * (c) 2005-2007 Sam Stephenson
  23. *
  24. * Prototype is freely distributable under the terms of an MIT-style license.
  25. * For details, see the Prototype web site: http://prototype.conio.net/
  26. *
  27. /*--------------------------------------------------------------------------*/
  28. //--------------------
  29. var Prototype = {
  30. Version: '1.5.0',
  31. BrowserFeatures: {
  32. XPath: !!document.evaluate
  33. },
  34. ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
  35. emptyFunction: function() {},
  36. K: function(x) { return x }
  37. }
  38. var Class = {
  39. create: function() {
  40. return function() {
  41. this.initialize.apply(this, arguments);
  42. }
  43. }
  44. }
  45. var Abstract = new Object();
  46. Object.extend = function(destination, source) {
  47. for (var property in source) {
  48. destination[property] = source[property];
  49. }
  50. return destination;
  51. }
  52. Object.extend(Object, {
  53. inspect: function(object) {
  54. try {
  55. if (object === undefined) return 'undefined';
  56. if (object === null) return 'null';
  57. return object.inspect ? object.inspect() : object.toString();
  58. } catch (e) {
  59. if (e instanceof RangeError) return '...';
  60. throw e;
  61. }
  62. },
  63. keys: function(object) {
  64. var keys = [];
  65. for (var property in object)
  66. keys.push(property);
  67. return keys;
  68. },
  69. values: function(object) {
  70. var values = [];
  71. for (var property in object)
  72. values.push(object[property]);
  73. return values;
  74. },
  75. clone: function(object) {
  76. return Object.extend({}, object);
  77. }
  78. });
  79. Function.prototype.bind = function() {
  80. var __method = this, args = $A(arguments), object = args.shift();
  81. return function() {
  82. return __method.apply(object, args.concat($A(arguments)));
  83. }
  84. }
  85. Function.prototype.bindAsEventListener = function(object) {
  86. var __method = this, args = $A(arguments), object = args.shift();
  87. return function(event) {
  88. return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
  89. }
  90. }
  91. Object.extend(Number.prototype, {
  92. toColorPart: function() {
  93. var digits = this.toString(16);
  94. if (this < 16) return '0' + digits;
  95. return digits;
  96. },
  97. succ: function() {
  98. return this + 1;
  99. },
  100. times: function(iterator) {
  101. $R(0, this, true).each(iterator);
  102. return this;
  103. }
  104. });
  105. var Try = {
  106. these: function() {
  107. var returnValue;
  108. for (var i = 0, length = arguments.length; i < length; i++) {
  109. var lambda = arguments[i];
  110. try {
  111. returnValue = lambda();
  112. break;
  113. } catch (e) {}
  114. }
  115. return returnValue;
  116. }
  117. }
  118. /*--------------------------------------------------------------------------*/
  119. var PeriodicalExecuter = Class.create();
  120. PeriodicalExecuter.prototype = {
  121. initialize: function(callback, frequency) {
  122. this.callback = callback;
  123. this.frequency = frequency;
  124. this.currentlyExecuting = false;
  125. this.registerCallback();
  126. },
  127. registerCallback: function() {
  128. this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  129. },
  130. stop: function() {
  131. if (!this.timer) return;
  132. clearInterval(this.timer);
  133. this.timer = null;
  134. },
  135. onTimerEvent: function() {
  136. if (!this.currentlyExecuting) {
  137. try {
  138. this.currentlyExecuting = true;
  139. this.callback(this);
  140. } finally {
  141. this.currentlyExecuting = false;
  142. }
  143. }
  144. }
  145. }
  146. String.interpret = function(value){
  147. return value == null ? '' : String(value);
  148. }
  149. Object.extend(String.prototype, {
  150. gsub: function(pattern, replacement) {
  151. var result = '', source = this, match;
  152. replacement = arguments.callee.prepareReplacement(replacement);
  153. while (source.length > 0) {
  154. if (match = source.match(pattern)) {
  155. result += source.slice(0, match.index);
  156. result += String.interpret(replacement(match));
  157. source = source.slice(match.index + match[0].length);
  158. } else {
  159. result += source, source = '';
  160. }
  161. }
  162. return result;
  163. },
  164. sub: function(pattern, replacement, count) {
  165. replacement = this.gsub.prepareReplacement(replacement);
  166. count = count === undefined ? 1 : count;
  167. return this.gsub(pattern, function(match) {
  168. if (--count < 0) return match[0];
  169. return replacement(match);
  170. });
  171. },
  172. scan: function(pattern, iterator) {
  173. this.gsub(pattern, iterator);
  174. return this;
  175. },
  176. truncate: function(length, truncation) {
  177. length = length || 30;
  178. truncation = truncation === undefined ? '...' : truncation;
  179. return this.length > length ?
  180. this.slice(0, length - truncation.length) + truncation : this;
  181. },
  182. strip: function() {
  183. return this.replace(/^\s+/, '').replace(/\s+$/, '');
  184. },
  185. stripTags: function() {
  186. return this.replace(/<\/?[^>]+>/gi, '');
  187. },
  188. stripScripts: function() {
  189. return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  190. },
  191. extractScripts: function() {
  192. var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
  193. var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
  194. return (this.match(matchAll) || []).map(function(scriptTag) {
  195. return (scriptTag.match(matchOne) || ['', ''])[1];
  196. });
  197. },
  198. evalScripts: function() {
  199. return this.extractScripts().map(function(script) { return eval(script) });
  200. },
  201. escapeHTML: function() {
  202. var div = document.createElement('div');
  203. var text = document.createTextNode(this);
  204. div.appendChild(text);
  205. return div.innerHTML;
  206. },
  207. unescapeHTML: function() {
  208. var div = document.createElement('div');
  209. div.innerHTML = this.stripTags();
  210. return div.childNodes[0] ? (div.childNodes.length > 1 ?
  211. $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) :
  212. div.childNodes[0].nodeValue) : '';
  213. },
  214. toQueryParams: function(separator) {
  215. var match = this.strip().match(/([^?#]*)(#.*)?$/);
  216. if (!match) return {};
  217. return match[1].split(separator || '&').inject({}, function(hash, pair) {
  218. if ((pair = pair.split('='))[0]) {
  219. var name = decodeURIComponent(pair[0]);
  220. var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;
  221. if (hash[name] !== undefined) {
  222. if (hash[name].constructor != Array)
  223. hash[name] = [hash[name]];
  224. if (value) hash[name].push(value);
  225. }
  226. else hash[name] = value;
  227. }
  228. return hash;
  229. });
  230. },
  231. toArray: function() {
  232. return this.split('');
  233. },
  234. succ: function() {
  235. return this.slice(0, this.length - 1) +
  236. String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  237. },
  238. camelize: function() {
  239. var parts = this.split('-'), len = parts.length;
  240. if (len == 1) return parts[0];
  241. var camelized = this.charAt(0) == '-'
  242. ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
  243. : parts[0];
  244. for (var i = 1; i < len; i++)
  245. camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
  246. return camelized;
  247. },
  248. capitalize: function(){
  249. return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  250. },
  251. underscore: function() {
  252. return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  253. },
  254. dasherize: function() {
  255. return this.gsub(/_/,'-');
  256. },
  257. inspect: function(useDoubleQuotes) {
  258. var escapedString = this.replace(/\\/g, '\\\\');
  259. if (useDoubleQuotes)
  260. return '"' + escapedString.replace(/"/g, '\\"') + '"';
  261. else
  262. return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  263. }
  264. });
  265. String.prototype.gsub.prepareReplacement = function(replacement) {
  266. if (typeof replacement == 'function') return replacement;
  267. var template = new Template(replacement);
  268. return function(match) { return template.evaluate(match) };
  269. }
  270. String.prototype.parseQuery = String.prototype.toQueryParams;
  271. var Template = Class.create();
  272. Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
  273. Template.prototype = {
  274. initialize: function(template, pattern) {
  275. this.template = template.toString();
  276. this.pattern = pattern || Template.Pattern;
  277. },
  278. evaluate: function(object) {
  279. return this.template.gsub(this.pattern, function(match) {
  280. var before = match[1];
  281. if (before == '\\') return match[2];
  282. return before + String.interpret(object[match[3]]);
  283. });
  284. }
  285. }
  286. var $break = new Object();
  287. var $continue = new Object();
  288. var Enumerable = {
  289. each: function(iterator) {
  290. var index = 0;
  291. try {
  292. this._each(function(value) {
  293. try {
  294. iterator(value, index++);
  295. } catch (e) {
  296. if (e != $continue) throw e;
  297. }
  298. });
  299. } catch (e) {
  300. if (e != $break) throw e;
  301. }
  302. return this;
  303. },
  304. eachSlice: function(number, iterator) {
  305. var index = -number, slices = [], array = this.toArray();
  306. while ((index += number) < array.length)
  307. slices.push(array.slice(index, index+number));
  308. return slices.map(iterator);
  309. },
  310. all: function(iterator) {
  311. var result = true;
  312. this.each(function(value, index) {
  313. result = result && !!(iterator || Prototype.K)(value, index);
  314. if (!result) throw $break;
  315. });
  316. return result;
  317. },
  318. any: function(iterator) {
  319. var result = false;
  320. this.each(function(value, index) {
  321. if (result = !!(iterator || Prototype.K)(value, index))
  322. throw $break;
  323. });
  324. return result;
  325. },
  326. collect: function(iterator) {
  327. var results = [];
  328. this.each(function(value, index) {
  329. results.push((iterator || Prototype.K)(value, index));
  330. });
  331. return results;
  332. },
  333. detect: function(iterator) {
  334. var result;
  335. this.each(function(value, index) {
  336. if (iterator(value, index)) {
  337. result = value;
  338. throw $break;
  339. }
  340. });
  341. return result;
  342. },
  343. findAll: function(iterator) {
  344. var results = [];
  345. this.each(function(value, index) {
  346. if (iterator(value, index))
  347. results.push(value);
  348. });
  349. return results;
  350. },
  351. grep: function(pattern, iterator) {
  352. var results = [];
  353. this.each(function(value, index) {
  354. var stringValue = value.toString();
  355. if (stringValue.match(pattern))
  356. results.push((iterator || Prototype.K)(value, index));
  357. })
  358. return results;
  359. },
  360. include: function(object) {
  361. var found = false;
  362. this.each(function(value) {
  363. if (value == object) {
  364. found = true;
  365. throw $break;
  366. }
  367. });
  368. return found;
  369. },
  370. inGroupsOf: function(number, fillWith) {
  371. fillWith = fillWith === undefined ? null : fillWith;
  372. return this.eachSlice(number, function(slice) {
  373. while(slice.length < number) slice.push(fillWith);
  374. return slice;
  375. });
  376. },
  377. inject: function(memo, iterator) {
  378. this.each(function(value, index) {
  379. memo = iterator(memo, value, index);
  380. });
  381. return memo;
  382. },
  383. invoke: function(method) {
  384. var args = $A(arguments).slice(1);
  385. return this.map(function(value) {
  386. return value[method].apply(value, args);
  387. });
  388. },
  389. max: function(iterator) {
  390. var result;
  391. this.each(function(value, index) {
  392. value = (iterator || Prototype.K)(value, index);
  393. if (result == undefined || value >= result)
  394. result = value;
  395. });
  396. return result;
  397. },
  398. min: function(iterator) {
  399. var result;
  400. this.each(function(value, index) {
  401. value = (iterator || Prototype.K)(value, index);
  402. if (result == undefined || value < result)
  403. result = value;
  404. });
  405. return result;
  406. },
  407. partition: function(iterator) {
  408. var trues = [], falses = [];
  409. this.each(function(value, index) {
  410. ((iterator || Prototype.K)(value, index) ?
  411. trues : falses).push(value);
  412. });
  413. return [trues, falses];
  414. },
  415. pluck: function(property) {
  416. var results = [];
  417. this.each(function(value, index) {
  418. results.push(value[property]);
  419. });
  420. return results;
  421. },
  422. reject: function(iterator) {
  423. var results = [];
  424. this.each(function(value, index) {
  425. if (!iterator(value, index))
  426. results.push(value);
  427. });
  428. return results;
  429. },
  430. sortBy: function(iterator) {
  431. return this.map(function(value, index) {
  432. return {value: value, criteria: iterator(value, index)};
  433. }).sort(function(left, right) {
  434. var a = left.criteria, b = right.criteria;
  435. return a < b ? -1 : a > b ? 1 : 0;
  436. }).pluck('value');
  437. },
  438. toArray: function() {
  439. return this.map();
  440. },
  441. zip: function() {
  442. var iterator = Prototype.K, args = $A(arguments);
  443. if (typeof args.last() == 'function')
  444. iterator = args.pop();
  445. var collections = [this].concat(args).map($A);
  446. return this.map(function(value, index) {
  447. return iterator(collections.pluck(index));
  448. });
  449. },
  450. size: function() {
  451. return this.toArray().length;
  452. },
  453. inspect: function() {
  454. return '#<Enumerable:' + this.toArray().inspect() + '>';
  455. }
  456. }
  457. Object.extend(Enumerable, {
  458. map: Enumerable.collect,
  459. find: Enumerable.detect,
  460. select: Enumerable.findAll,
  461. member: Enumerable.include,
  462. entries: Enumerable.toArray
  463. });
  464. var $A = Array.from = function(iterable) {
  465. if (!iterable) return [];
  466. if (iterable.toArray) {
  467. return iterable.toArray();
  468. } else {
  469. var results = [];
  470. for (var i = 0, length = iterable.length; i < length; i++)
  471. results.push(iterable[i]);
  472. return results;
  473. }
  474. }
  475. Object.extend(Array.prototype, Enumerable);
  476. if (!Array.prototype._reverse)
  477. Array.prototype._reverse = Array.prototype.reverse;
  478. Object.extend(Array.prototype, {
  479. _each: function(iterator) {
  480. for (var i = 0, length = this.length; i < length; i++)
  481. iterator(this[i]);
  482. },
  483. clear: function() {
  484. this.length = 0;
  485. return this;
  486. },
  487. first: function() {
  488. return this[0];
  489. },
  490. last: function() {
  491. return this[this.length - 1];
  492. },
  493. compact: function() {
  494. return this.select(function(value) {
  495. return value != null;
  496. });
  497. },
  498. flatten: function() {
  499. return this.inject([], function(array, value) {
  500. return array.concat(value && value.constructor == Array ?
  501. value.flatten() : [value]);
  502. });
  503. },
  504. without: function() {
  505. var values = $A(arguments);
  506. return this.select(function(value) {
  507. return !values.include(value);
  508. });
  509. },
  510. indexOf: function(object) {
  511. for (var i = 0, length = this.length; i < length; i++)
  512. if (this[i] == object) return i;
  513. return -1;
  514. },
  515. reverse: function(inline) {
  516. return (inline !== false ? this : this.toArray())._reverse();
  517. },
  518. reduce: function() {
  519. return this.length > 1 ? this : this[0];
  520. },
  521. uniq: function() {
  522. return this.inject([], function(array, value) {
  523. return array.include(value) ? array : array.concat([value]);
  524. });
  525. },
  526. clone: function() {
  527. return [].concat(this);
  528. },
  529. size: function() {
  530. return this.length;
  531. },
  532. inspect: function() {
  533. return '[' + this.map(Object.inspect).join(', ') + ']';
  534. }
  535. });
  536. Array.prototype.toArray = Array.prototype.clone;
  537. function $w(string){
  538. string = string.strip();
  539. return string ? string.split(/\s+/) : [];
  540. }
  541. if(window.opera){
  542. Array.prototype.concat = function(){
  543. var array = [];
  544. for(var i = 0, length = this.length; i < length; i++) array.push(this[i]);
  545. for(var i = 0, length = arguments.length; i < length; i++) {
  546. if(arguments[i].constructor == Array) {
  547. for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
  548. array.push(arguments[i][j]);
  549. } else {
  550. array.push(arguments[i]);
  551. }
  552. }
  553. return array;
  554. }
  555. }
  556. var Hash = function(obj) {
  557. Object.extend(this, obj || {});
  558. };
  559. Object.extend(Hash, {
  560. toQueryString: function(obj) {
  561. var parts = [];
  562. this.prototype._each.call(obj, function(pair) {
  563. if (!pair.key) return;
  564. if (pair.value && pair.value.constructor == Array) {
  565. var values = pair.value.compact();
  566. if (values.length < 2) pair.value = values.reduce();
  567. else {
  568. key = encodeURIComponent(pair.key);
  569. values.each(function(value) {
  570. value = value != undefined ? encodeURIComponent(value) : '';
  571. parts.push(key + '=' + encodeURIComponent(value));
  572. });
  573. return;
  574. }
  575. }
  576. if (pair.value == undefined) pair[1] = '';
  577. parts.push(pair.map(encodeURIComponent).join('='));
  578. });
  579. return parts.join('&');
  580. }
  581. });
  582. Object.extend(Hash.prototype, Enumerable);
  583. Object.extend(Hash.prototype, {
  584. _each: function(iterator) {
  585. for (var key in this) {
  586. var value = this[key];
  587. if (value && value == Hash.prototype[key]) continue;
  588. var pair = [key, value];
  589. pair.key = key;
  590. pair.value = value;
  591. iterator(pair);
  592. }
  593. },
  594. keys: function() {
  595. return this.pluck('key');
  596. },
  597. values: function() {
  598. return this.pluck('value');
  599. },
  600. merge: function(hash) {
  601. return $H(hash).inject(this, function(mergedHash, pair) {
  602. mergedHash[pair.key] = pair.value;
  603. return mergedHash;
  604. });
  605. },
  606. remove: function() {
  607. var result;
  608. for(var i = 0, length = arguments.length; i < length; i++) {
  609. var value = this[arguments[i]];
  610. if (value !== undefined){
  611. if (result === undefined) result = value;
  612. else {
  613. if (result.constructor != Array) result = [result];
  614. result.push(value)
  615. }
  616. }
  617. delete this[arguments[i]];
  618. }
  619. return result;
  620. },
  621. toQueryString: function() {
  622. return Hash.toQueryString(this);
  623. },
  624. inspect: function() {
  625. return '#<Hash:{' + this.map(function(pair) {
  626. return pair.map(Object.inspect).join(': ');
  627. }).join(', ') + '}>';
  628. }
  629. });
  630. function $H(object) {
  631. if (object && object.constructor == Hash) return object;
  632. return new Hash(object);
  633. };
  634. ObjectRange = Class.create();
  635. Object.extend(ObjectRange.prototype, Enumerable);
  636. Object.extend(ObjectRange.prototype, {
  637. initialize: function(start, end, exclusive) {
  638. this.start = start;
  639. this.end = end;
  640. this.exclusive = exclusive;
  641. },
  642. _each: function(iterator) {
  643. var value = this.start;
  644. while (this.include(value)) {
  645. iterator(value);
  646. value = value.succ();
  647. }
  648. },
  649. include: function(value) {
  650. if (value < this.start)
  651. return false;
  652. if (this.exclusive)
  653. return value < this.end;
  654. return value <= this.end;
  655. }
  656. });
  657. var $R = function(start, end, exclusive) {
  658. return new ObjectRange(start, end, exclusive);
  659. }
  660. var Ajax = {
  661. getTransport: function() {
  662. return Try.these(
  663. function() {return new XMLHttpRequest()},
  664. function() {return new ActiveXObject('Msxml2.XMLHTTP')},
  665. function() {return new ActiveXObject('Microsoft.XMLHTTP')}
  666. ) || false;
  667. },
  668. activeRequestCount: 0
  669. }
  670. Ajax.Responders = {
  671. responders: [],
  672. _each: function(iterator) {
  673. this.responders._each(iterator);
  674. },
  675. register: function(responder) {
  676. if (!this.include(responder))
  677. this.responders.push(responder);
  678. },
  679. unregister: function(responder) {
  680. this.responders = this.responders.without(responder);
  681. },
  682. dispatch: function(callback, request, transport, json) {
  683. this.each(function(responder) {
  684. if (typeof responder[callback] == 'function') {
  685. try {
  686. responder[callback].apply(responder, [request, transport, json]);
  687. } catch (e) {}
  688. }
  689. });
  690. }
  691. };
  692. Object.extend(Ajax.Responders, Enumerable);
  693. Ajax.Responders.register({
  694. onCreate: function() {
  695. Ajax.activeRequestCount++;
  696. },
  697. onComplete: function() {
  698. Ajax.activeRequestCount--;
  699. }
  700. });
  701. Ajax.Base = function() {};
  702. Ajax.Base.prototype = {
  703. setOptions: function(options) {
  704. this.options = {
  705. method: 'post',
  706. asynchronous: true,
  707. contentType: 'application/x-www-form-urlencoded',
  708. encoding: 'UTF-8',
  709. parameters: ''
  710. }
  711. Object.extend(this.options, options || {});
  712. this.options.method = this.options.method.toLowerCase();
  713. if (typeof this.options.parameters == 'string')
  714. this.options.parameters = this.options.parameters.toQueryParams();
  715. }
  716. }
  717. Ajax.Request = Class.create();
  718. Ajax.Request.Events =
  719. ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
  720. Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  721. _complete: false,
  722. initialize: function(url, options) {
  723. this.transport = Ajax.getTransport();
  724. this.setOptions(options);
  725. this.request(url);
  726. },
  727. request: function(url) {
  728. this.url = url;
  729. this.method = this.options.method;
  730. var params = this.options.parameters;
  731. if (!['get', 'post'].include(this.method)) {
  732. // simulate other verbs over post
  733. params['_method'] = this.method;
  734. this.method = 'post';
  735. }
  736. params = Hash.toQueryString(params);
  737. if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_='
  738. // when GET, append parameters to URL
  739. if (this.method == 'get' && params)
  740. this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params;
  741. try {
  742. Ajax.Responders.dispatch('onCreate', this, this.transport);
  743. this.transport.open(this.method.toUpperCase(), this.url,
  744. this.options.asynchronous);
  745. if (this.options.asynchronous)
  746. setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);
  747. this.transport.onreadystatechange = this.onStateChange.bind(this);
  748. this.setRequestHeaders();
  749. var body = this.method == 'post' ? (this.options.postBody || params) : null;
  750. this.transport.send(body);
  751. /* Force Firefox to handle ready state 4 for synchronous requests */
  752. if (!this.options.asynchronous && this.transport.overrideMimeType)
  753. this.onStateChange();
  754. }
  755. catch (e) {
  756. this.dispatchException(e);
  757. }
  758. },
  759. onStateChange: function() {
  760. var readyState = this.transport.readyState;
  761. if (readyState > 1 && !((readyState == 4) && this._complete))
  762. this.respondToReadyState(this.transport.readyState);
  763. },
  764. setRequestHeaders: function() {
  765. var headers = {
  766. 'X-Requested-With': 'XMLHttpRequest',
  767. 'X-Prototype-Version': Prototype.Version,
  768. 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  769. };
  770. if (this.method == 'post') {
  771. headers['Content-type'] = this.options.contentType +
  772. (this.options.encoding ? '; charset=' + this.options.encoding : '');
  773. /* Force "Connection: close" for older Mozilla browsers to work
  774. * around a bug where XMLHttpRequest sends an incorrect
  775. * Content-length header. See Mozilla Bugzilla #246651.
  776. */
  777. if (this.transport.overrideMimeType &&
  778. (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
  779. headers['Connection'] = 'close';
  780. }
  781. // user-defined headers
  782. if (typeof this.options.requestHeaders == 'object') {
  783. var extras = this.options.requestHeaders;
  784. if (typeof extras.push == 'function')
  785. for (var i = 0, length = extras.length; i < length; i += 2)
  786. headers[extras[i]] = extras[i+1];
  787. else
  788. $H(extras).each(function(pair) { headers[pair.key] = pair.value });
  789. }
  790. for (var name in headers)
  791. this.transport.setRequestHeader(name, headers[name]);
  792. },
  793. success: function() {
  794. return !this.transport.status
  795. || (this.transport.status >= 200 && this.transport.status < 300);
  796. },
  797. respondToReadyState: function(readyState) {
  798. var state = Ajax.Request.Events[readyState];
  799. var transport = this.transport, json = this.evalJSON();
  800. if (state == 'Complete') {
  801. try {
  802. this._complete = true;
  803. (this.options['on' + this.transport.status]
  804. || this.options['on' + (this.success() ? 'Success' : 'Failure')]
  805. || Prototype.emptyFunction)(transport, json);
  806. } catch (e) {
  807. this.dispatchException(e);
  808. }
  809. if ((this.getHeader('Content-type') || 'text/javascript').strip().
  810. match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
  811. this.evalResponse();
  812. }
  813. try {
  814. (this.options['on' + state] || Prototype.emptyFunction)(transport, json);
  815. Ajax.Responders.dispatch('on' + state, this, transport, json);
  816. } catch (e) {
  817. this.dispatchException(e);
  818. }
  819. if (state == 'Complete') {
  820. // avoid memory leak in MSIE: clean up
  821. this.transport.onreadystatechange = Prototype.emptyFunction;
  822. }
  823. },
  824. getHeader: function(name) {
  825. try {
  826. return this.transport.getResponseHeader(name);
  827. } catch (e) { return null }
  828. },
  829. evalJSON: function() {
  830. try {
  831. var json = this.getHeader('X-JSON');
  832. return json ? eval('(' + json + ')') : null;
  833. } catch (e) { return null }
  834. },
  835. evalResponse: function() {
  836. try {
  837. return eval(this.transport.responseText);
  838. } catch (e) {
  839. this.dispatchException(e);
  840. }
  841. },
  842. dispatchException: function(exception) {
  843. (this.options.onException || Prototype.emptyFunction)(this, exception);
  844. Ajax.Responders.dispatch('onException', this, exception);
  845. }
  846. });
  847. Ajax.Updater = Class.create();
  848. Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  849. initialize: function(container, url, options) {
  850. this.container = {
  851. success: (container.success || container),
  852. failure: (container.failure || (container.success ? null : container))
  853. }
  854. this.transport = Ajax.getTransport();
  855. this.setOptions(options);
  856. var onComplete = this.options.onComplete || Prototype.emptyFunction;
  857. this.options.onComplete = (function(transport, param) {
  858. this.updateContent();
  859. onComplete(transport, param);
  860. }).bind(this);
  861. this.request(url);
  862. },
  863. updateContent: function() {
  864. var receiver = this.container[this.success() ? 'success' : 'failure'];
  865. var response = this.transport.responseText;
  866. if (!this.options.evalScripts) response = response.stripScripts();
  867. if (receiver = $(receiver)) {
  868. if (this.options.insertion)
  869. new this.options.insertion(receiver, response);
  870. else
  871. receiver.update(response);
  872. }
  873. if (this.success()) {
  874. if (this.onComplete)
  875. setTimeout(this.onComplete.bind(this), 10);
  876. }
  877. }
  878. });
  879. Ajax.PeriodicalUpdater = Class.create();
  880. Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  881. initialize: function(container, url, options) {
  882. this.setOptions(options);
  883. this.onComplete = this.options.onComplete;
  884. this.frequency = (this.options.frequency || 2);
  885. this.decay = (this.options.decay || 1);
  886. this.updater = {};
  887. this.container = container;
  888. this.url = url;
  889. this.start();
  890. },
  891. start: function() {
  892. this.options.onComplete = this.updateComplete.bind(this);
  893. this.onTimerEvent();
  894. },
  895. stop: function() {
  896. this.updater.options.onComplete = undefined;
  897. clearTimeout(this.timer);
  898. (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  899. },
  900. updateComplete: function(request) {
  901. if (this.options.decay) {
  902. this.decay = (request.responseText == this.lastText ?
  903. this.decay * this.options.decay : 1);
  904. this.lastText = request.responseText;
  905. }
  906. this.timer = setTimeout(this.onTimerEvent.bind(this),
  907. this.decay * this.frequency * 1000);
  908. },
  909. onTimerEvent: function() {
  910. this.updater = new Ajax.Updater(this.container, this.url, this.options);
  911. }
  912. });
  913. function $(element) {
  914. if (arguments.length > 1) {
  915. for (var i = 0, elements = [], length = arguments.length; i < length; i++)
  916. elements.push($(arguments[i]));
  917. return elements;
  918. }
  919. if (typeof element == 'string')
  920. element = document.getElementById(element);
  921. return Element.extend(element);
  922. }
  923. if (Prototype.BrowserFeatures.XPath) {
  924. document._getElementsByXPath = function(expression, parentElement) {
  925. var results = [];
  926. var query = document.evaluate(expression, $(parentElement) || document,
  927. null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  928. for (var i = 0, length = query.snapshotLength; i < length; i++)
  929. results.push(query.snapshotItem(i));
  930. return results;
  931. };
  932. }
  933. document.getElementsByClassName = function(className, parentElement) {
  934. if (Prototype.BrowserFeatures.XPath) {
  935. var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
  936. return document._getElementsByXPath(q, parentElement);
  937. } else {
  938. var children = ($(parentElement) || document.body).getElementsByTagName('*');
  939. var elements = [], child;
  940. for (var i = 0, length = children.length; i < length; i++) {
  941. child = children[i];
  942. if (Element.hasClassName(child, className))
  943. elements.push(Element.extend(child));
  944. }
  945. return elements;
  946. }
  947. };
  948. /*--------------------------------------------------------------------------*/
  949. if (!window.Element)
  950. var Element = new Object();
  951. Element.extend = function(element) {
  952. if (!element || _nativeExtensions || element.nodeType == 3) return element;
  953. if (!element._extended && element.tagName && element != window) {
  954. var methods = Object.clone(Element.Methods), cache = Element.extend.cache;
  955. if (element.tagName == 'FORM')
  956. Object.extend(methods, Form.Methods);
  957. if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName))
  958. Object.extend(methods, Form.Element.Methods);
  959. Object.extend(methods, Element.Methods.Simulated);
  960. for (var property in methods) {
  961. var value = methods[property];
  962. if (typeof value == 'function' && !(property in element))
  963. element[property] = cache.findOrStore(value);
  964. }
  965. }
  966. element._extended = true;
  967. return element;
  968. };
  969. Element.extend.cache = {
  970. findOrStore: function(value) {
  971. return this[value] = this[value] || function() {
  972. return value.apply(null, [this].concat($A(arguments)));
  973. }
  974. }
  975. };
  976. Element.Methods = {
  977. visible: function(element) {
  978. return $(element).style.display != 'none';
  979. },
  980. toggle: function(element) {
  981. element = $(element);
  982. Element[Element.visible(element) ? 'hide' : 'show'](element);
  983. return element;
  984. },
  985. hide: function(element) {
  986. $(element).style.display = 'none';
  987. return element;
  988. },
  989. show: function(element) {
  990. $(element).style.display = '';
  991. return element;
  992. },
  993. remove: function(element) {
  994. element = $(element);
  995. element.parentNode.removeChild(element);
  996. return element;
  997. },
  998. update: function(element, html) {
  999. html = typeof html == 'undefined' ? '' : html.toString();
  1000. $(element).innerHTML = html.stripScripts();
  1001. setTimeout(function() {html.evalScripts()}, 10);
  1002. return element;
  1003. },
  1004. replace: function(element, html) {
  1005. element = $(element);
  1006. html = typeof html == 'undefined' ? '' : html.toString();
  1007. if (element.outerHTML) {
  1008. element.outerHTML = html.stripScripts();
  1009. } else {
  1010. var range = element.ownerDocument.createRange();
  1011. range.selectNodeContents(element);
  1012. element.parentNode.replaceChild(
  1013. range.createContextualFragment(html.stripScripts()), element);
  1014. }
  1015. setTimeout(function() {html.evalScripts()}, 10);
  1016. return element;
  1017. },
  1018. inspect: function(element) {
  1019. element = $(element);
  1020. var result = '<' + element.tagName.toLowerCase();
  1021. $H({'id': 'id', 'className': 'class'}).each(function(pair) {
  1022. var property = pair.first(), attribute = pair.last();
  1023. var value = (element[property] || '').toString();
  1024. if (value) result += ' ' + attribute + '=' + value.inspect(true);
  1025. });
  1026. return result + '>';
  1027. },
  1028. recursivelyCollect: function(element, property) {
  1029. element = $(element);
  1030. var elements = [];
  1031. while (element = element[property])
  1032. if (element.nodeType == 1)
  1033. elements.push(Element.extend(element));
  1034. return elements;
  1035. },
  1036. ancestors: function(element) {
  1037. return $(element).recursivelyCollect('parentNode');
  1038. },
  1039. descendants: function(element) {
  1040. return $A($(element).getElementsByTagName('*'));
  1041. },
  1042. immediateDescendants: function(element) {
  1043. if (!(element = $(element).firstChild)) return [];
  1044. while (element && element.nodeType != 1) element = element.nextSibling;
  1045. if (element) return [element].concat($(element).nextSiblings());
  1046. return [];
  1047. },
  1048. previousSiblings: function(element) {
  1049. return $(element).recursivelyCollect('previousSibling');
  1050. },
  1051. nextSiblings: function(element) {
  1052. return $(element).recursivelyCollect('nextSibling');
  1053. },
  1054. siblings: function(element) {
  1055. element = $(element);
  1056. return element.previousSiblings().reverse().concat(element.nextSiblings());
  1057. },
  1058. match: function(element, selector) {
  1059. if (typeof selector == 'string')
  1060. selector = new Selector(selector);
  1061. return selector.match($(element));
  1062. },
  1063. up: function(element, expression, index) {
  1064. return Selector.findElement($(element).ancestors(), expression, index);
  1065. },
  1066. down: function(element, expression, index) {
  1067. return Selector.findElement($(element).descendants(), expression, index);
  1068. },
  1069. previous: function(element, expression, index) {
  1070. return Selector.findElement($(element).previousSiblings(), expression, index);
  1071. },
  1072. next: function(element, expression, index) {
  1073. return Selector.findElement($(element).nextSiblings(), expression, index);
  1074. },
  1075. getElementsBySelector: function() {
  1076. var args = $A(arguments), element = $(args.shift());
  1077. return Selector.findChildElements(element, args);
  1078. },
  1079. getElementsByClassName: function(element, className) {
  1080. return document.getElementsByClassName(className, element);
  1081. },
  1082. readAttribute: function(element, name) {
  1083. element = $(element);
  1084. if (document.all && !window.opera) {
  1085. var t = Element._attributeTranslations;
  1086. if (t.values[name]) return t.values[name](element, name);
  1087. if (t.names[name]) name = t.names[name];
  1088. var attribute = element.attributes[name];
  1089. if(attribute) return attribute.nodeValue;
  1090. }
  1091. return element.getAttribute(name);
  1092. },
  1093. getHeight: function(element) {
  1094. return $(element).getDimensions().height;
  1095. },
  1096. getWidth: function(element) {
  1097. return $(element).getDimensions().width;
  1098. },
  1099. classNames: function(element) {
  1100. return new Element.ClassNames(element);
  1101. },
  1102. hasClassName: function(element, className) {
  1103. if (!(element = $(element))) return;
  1104. var elementClassName = element.className;
  1105. if (elementClassName.length == 0) return false;
  1106. if (elementClassName == className ||
  1107. elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
  1108. return true;
  1109. return false;
  1110. },
  1111. addClassName: function(element, className) {
  1112. if (!(element = $(element))) return;
  1113. Element.classNames(element).add(className);
  1114. return element;
  1115. },
  1116. removeClassName: function(element, className) {
  1117. if (!(element = $(element))) return;
  1118. Element.classNames(element).remove(className);
  1119. return element;
  1120. },
  1121. toggleClassName: function(element, className) {
  1122. if (!(element = $(element))) return;
  1123. Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className);
  1124. return element;
  1125. },
  1126. observe: function() {
  1127. Event.observe.apply(Event, arguments);
  1128. return $A(arguments).first();
  1129. },
  1130. stopObserving: function() {
  1131. Event.stopObserving.apply(Event, arguments);
  1132. return $A(arguments).first();
  1133. },
  1134. // removes whitespace-only text node children
  1135. cleanWhitespace: function(element) {
  1136. element = $(element);
  1137. var node = element.firstChild;
  1138. while (node) {
  1139. var nextNode = node.nextSibling;
  1140. if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
  1141. element.removeChild(node);
  1142. node = nextNode;
  1143. }
  1144. return element;
  1145. },
  1146. empty: function(element) {
  1147. return $(element).innerHTML.match(/^\s*$/);
  1148. },
  1149. descendantOf: function(element, ancestor) {
  1150. element = $(element), ancestor = $(ancestor);
  1151. while (element = element.parentNode)
  1152. if (element == ancestor) return true;
  1153. return false;
  1154. },
  1155. scrollTo: function(element) {
  1156. element = $(element);
  1157. var pos = Position.cumulativeOffset(element);
  1158. window.scrollTo(pos[0], pos[1]);
  1159. return element;
  1160. },
  1161. getStyle: function(element, style) {
  1162. element = $(element);
  1163. if (['float','cssFloat'].include(style))
  1164. style = (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat');
  1165. style = style.camelize();
  1166. var value = element.style[style];
  1167. if (!value) {
  1168. if (document.defaultView && document.defaultView.getComputedStyle) {
  1169. var css = document.defaultView.getComputedStyle(element, null);
  1170. value = css ? css[style] : null;
  1171. } else if (element.currentStyle) {
  1172. value = element.currentStyle[style];
  1173. }
  1174. }
  1175. if((value == 'auto') && ['width','height'].include(style) && (element.getStyle('display') != 'none'))
  1176. value = element['offset'+style.capitalize()] + 'px';
  1177. if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
  1178. if (Element.getStyle(element, 'position') == 'static') value = 'auto';
  1179. if(style == 'opacity') {
  1180. if(value) return parseFloat(value);
  1181. if(value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
  1182. if(value[1]) return parseFloat(value[1]) / 100;
  1183. return 1.0;
  1184. }
  1185. return value == 'auto' ? null : value;
  1186. },
  1187. setStyle: function(element, style) {
  1188. element = $(element);
  1189. for (var name in style) {
  1190. var value = style[name];
  1191. if(name == 'opacity') {
  1192. if (value == 1) {
  1193. value = (/Gecko/.test(navigator.userAgent) &&
  1194. !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0;
  1195. if(/MSIE/.test(navigator.userAgent) && !window.opera)
  1196. element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
  1197. } else if(value == '') {
  1198. if(/MSIE/.test(navigator.userAgent) && !window.opera)
  1199. element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
  1200. } else {
  1201. if(value < 0.00001) value = 0;
  1202. if(/MSIE/.test(navigator.userAgent) && !window.opera)
  1203. element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') +
  1204. 'alpha(opacity='+value*100+')';
  1205. }
  1206. } else if(['float','cssFloat'].include(name)) name = (typeof element.style.styleFloat != 'undefined') ? 'styleFloat' : 'cssFloat';
  1207. element.style[name.camelize()] = value;
  1208. }
  1209. return element;
  1210. },
  1211. getDimensions: function(element) {
  1212. element = $(element);
  1213. var display = $(element).getStyle('display');
  1214. if (display != 'none' && display != null) // Safari bug
  1215. return {width: element.offsetWidth, height: element.offsetHeight};
  1216. // All *Width and *Height properties give 0 on elements with display none,
  1217. // so enable the element temporarily
  1218. var els = element.style;
  1219. var originalVisibility = els.visibility;
  1220. var originalPosition = els.position;
  1221. var originalDisplay = els.display;
  1222. els.visibility = 'hidden';
  1223. els.position = 'absolute';
  1224. els.display = 'block';
  1225. var originalWidth = element.clientWidth;
  1226. var originalHeight = element.clientHeight;
  1227. els.display = originalDisplay;
  1228. els.position = originalPosition;
  1229. els.visibility = originalVisibility;
  1230. return {width: originalWidth, height: originalHeight};
  1231. },
  1232. makePositioned: function(element) {
  1233. element = $(element);
  1234. var pos = Element.getStyle(element, 'position');
  1235. if (pos == 'static' || !pos) {
  1236. element._madePositioned = true;
  1237. element.style.position = 'relative';
  1238. // Opera returns the offset relative to the positioning context, when an
  1239. // element is position relative but top and left have not been defined
  1240. if (window.opera) {
  1241. element.style.top = 0;
  1242. element.style.left = 0;
  1243. }
  1244. }
  1245. return element;
  1246. },
  1247. undoPositioned: function(element) {
  1248. element = $(element);
  1249. if (element._madePositioned) {
  1250. element._madePositioned = undefined;
  1251. element.style.position =
  1252. element.style.top =
  1253. element.style.left =
  1254. element.style.bottom =
  1255. element.style.right = '';
  1256. }
  1257. return element;
  1258. },
  1259. makeClipping: function(element) {
  1260. element = $(element);
  1261. if (element._overflow) return element;
  1262. element._overflow = element.style.overflow || 'auto';
  1263. if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
  1264. element.style.overflow = 'hidden';
  1265. return element;
  1266. },
  1267. undoClipping: function(element) {
  1268. element = $(element);
  1269. if (!element._overflow) return element;
  1270. element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
  1271. element._overflow = null;
  1272. return element;
  1273. }
  1274. };
  1275. Object.extend(Element.Methods, {childOf: Element.Methods.descendantOf});
  1276. Element._attributeTranslations = {};
  1277. Element._attributeTranslations.names = {
  1278. colspan: "colSpan",
  1279. rowspan: "rowSpan",
  1280. valign: "vAlign",
  1281. datetime: "dateTime",
  1282. accesskey: "accessKey",
  1283. tabindex: "tabIndex",
  1284. enctype: "encType",
  1285. maxlength: "maxLength",
  1286. readonly: "readOnly",
  1287. longdesc: "longDesc"
  1288. };
  1289. Element._attributeTranslations.values = {
  1290. _getAttr: function(element, attribute) {
  1291. return element.getAttribute(attribute, 2);
  1292. },
  1293. _flag: function(element, attribute) {
  1294. return $(element).hasAttribute(attribute) ? attribute : null;
  1295. },
  1296. style: function(element) {
  1297. return element.style.cssText.toLowerCase();
  1298. },
  1299. title: function(element) {
  1300. var node = element.getAttributeNode('title');
  1301. return node.specified ? node.nodeValue : null;
  1302. }
  1303. };
  1304. Object.extend(Element._attributeTranslations.values, {
  1305. href: Element._attributeTranslations.values._getAttr,
  1306. src: Element._attributeTranslations.values._getAttr,
  1307. disabled: Element._attributeTranslations.values._flag,
  1308. checked: Element._attributeTranslations.values._flag,
  1309. readonly: Element._attributeTranslations.values._flag,
  1310. multiple: Element._attributeTranslations.values._flag
  1311. });
  1312. Element.Methods.Simulated = {
  1313. hasAttribute: function(element, attribute) {
  1314. var t = Element._attributeTranslations;
  1315. attribute = t.names[attribute] || attribute;
  1316. return $(element).getAttributeNode(attribute).specified;
  1317. }
  1318. };
  1319. // IE is missing .innerHTML support for TABLE-related elements
  1320. if (document.all && !window.opera){
  1321. Element.Methods.update = function(element, html) {
  1322. element = $(element);
  1323. html = typeof html == 'undefined' ? '' : html.toString();
  1324. var tagName = element.tagName.toUpperCase();
  1325. if (['THEAD','TBODY','TR','TD'].include(tagName)) {
  1326. var div = document.createElement('div');
  1327. switch (tagName) {
  1328. case 'THEAD':
  1329. case 'TBODY':
  1330. div.innerHTML = '<table><tbody>' + html.stripScripts() + '</tbody></table>';
  1331. depth = 2;
  1332. break;
  1333. case 'TR':
  1334. div.innerHTML = '<table><tbody><tr>' + html.stripScripts() + '</tr></tbody></table>';
  1335. depth = 3;
  1336. break;
  1337. case 'TD':
  1338. div.innerHTML = '<table><tbody><tr><td>' + html.stripScripts() + '</td></tr></tbody></table>';
  1339. depth = 4;
  1340. }
  1341. $A(element.childNodes).each(function(node){
  1342. element.removeChild(node)
  1343. });
  1344. depth.times(function(){ div = div.firstChild });
  1345. $A(div.childNodes).each(
  1346. function(node){ element.appendChild(node) });
  1347. } else {
  1348. element.innerHTML = html.stripScripts();
  1349. }
  1350. setTimeout(function() {html.evalScripts()}, 10);
  1351. return element;
  1352. }
  1353. };
  1354. Object.extend(Element, Element.Methods);
  1355. var _nativeExtensions = false;
  1356. if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
  1357. ['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) {
  1358. var className = 'HTML' + tag + 'Element';
  1359. if(window[className]) return;
  1360. var klass = window[className] = {};
  1361. klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__;
  1362. });
  1363. Element.addMethods = function(methods) {
  1364. Object.extend(Element.Methods, methods || {});
  1365. function copy(methods, destination, onlyIfAbsent) {
  1366. onlyIfAbsent = onlyIfAbsent || false;
  1367. var cache = Element.extend.cache;
  1368. for (var property in methods) {
  1369. var value = methods[property];
  1370. if (!onlyIfAbsent || !(property in destination))
  1371. destination[property] = cache.findOrStore(value);
  1372. }
  1373. }
  1374. if (typeof HTMLElement != 'undefined') {
  1375. copy(Element.Methods, HTMLElement.prototype);
  1376. copy(Element.Methods.Simulated, HTMLElement.prototype, true);
  1377. copy(Form.Methods, HTMLFormElement.prototype);
  1378. [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) {
  1379. copy(Form.Element.Methods, klass.prototype);
  1380. });
  1381. _nativeExtensions = true;
  1382. }
  1383. }
  1384. var Toggle = new Object();
  1385. Toggle.display = Element.toggle;
  1386. /*--------------------------------------------------------------------------*/
  1387. Abstract.Insertion = function(adjacency) {
  1388. this.adjacency = adjacency;
  1389. }
  1390. Abstract.Insertion.prototype = {
  1391. initialize: function(element, content) {
  1392. this.element = $(element);
  1393. this.content = content.stripScripts();
  1394. if (this.adjacency && this.element.insertAdjacentHTML) {
  1395. try {
  1396. this.element.insertAdjacentHTML(this.adjacency, this.content);
  1397. } catch (e) {
  1398. var tagName = this.element.tagName.toUpperCase();
  1399. if (['TBODY', 'TR'].include(tagName)) {
  1400. this.insertContent(this.contentFromAnonymousTable());
  1401. } else {
  1402. throw e;
  1403. }
  1404. }
  1405. } else {
  1406. this.range = this.element.ownerDocument.createRange();
  1407. if (this.initializeRange) this.initializeRange();
  1408. this.insertContent([this.range.createContextualFragment(this.content)]);
  1409. }
  1410. setTimeout(function() {content.evalScripts()}, 10);
  1411. },
  1412. contentFromAnonymousTable: function() {
  1413. var div = document.createElement('div');
  1414. div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
  1415. return $A(div.childNodes[0].childNodes[0].childNodes);
  1416. }
  1417. }
  1418. var Insertion = new Object();
  1419. Insertion.Before = Class.create();
  1420. Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  1421. initializeRange: function() {
  1422. this.range.setStartBefore(this.element);
  1423. },
  1424. insertContent: function(fragments) {
  1425. fragments.each((function(fragment) {
  1426. this.element.parentNode.insertBefore(fragment, this.element);
  1427. }).bind(this));
  1428. }
  1429. });
  1430. Insertion.Top = Class.create();
  1431. Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  1432. initializeRange: function() {
  1433. this.range.selectNodeContents(this.element);
  1434. this.range.collapse(true);
  1435. },
  1436. insertContent: function(fragments) {
  1437. fragments.reverse(false).each((function(fragment) {
  1438. this.element.insertBefore(fragment, this.element.firstChild);
  1439. }).bind(this));
  1440. }
  1441. });
  1442. Insertion.Bottom = Class.create();
  1443. Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  1444. initializeRange: function() {
  1445. this.range.selectNodeContents(this.element);
  1446. this.range.collapse(this.element);
  1447. },
  1448. insertContent: function(fragments) {
  1449. fragments.each((function(fragment) {
  1450. this.element.appendChild(fragment);
  1451. }).bind(this));
  1452. }
  1453. });
  1454. Insertion.After = Class.create();
  1455. Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  1456. initializeRange: function() {
  1457. this.range.setStartAfter(this.element);
  1458. },
  1459. insertContent: function(fragments) {
  1460. fragments.each((function(fragment) {
  1461. this.element.parentNode.insertBefore(fragment,
  1462. this.element.nextSibling);
  1463. }).bind(this));
  1464. }
  1465. });
  1466. /*--------------------------------------------------------------------------*/
  1467. Element.ClassNames = Class.create();
  1468. Element.ClassNames.prototype = {
  1469. initialize: function(element) {
  1470. this.element = $(element);
  1471. },
  1472. _each: function(iterator) {
  1473. this.element.className.split(/\s+/).select(function(name) {
  1474. return name.length > 0;
  1475. })._each(iterator);
  1476. },
  1477. set: function(className) {
  1478. this.element.className = className;
  1479. },
  1480. add: function(classNameToAdd) {
  1481. if (this.include(classNameToAdd)) return;
  1482. this.set($A(this).concat(classNameToAdd).join(' '));
  1483. },
  1484. remove: function(classNameToRemove) {
  1485. if (!this.include(classNameToRemove)) return;
  1486. this.set($A(this).without(classNameToRemove).join(' '));
  1487. },
  1488. toString: function() {
  1489. return $A(this).join(' ');
  1490. }
  1491. };
  1492. Object.extend(Element.ClassNames.prototype, Enumerable);
  1493. var Selector = Class.create();
  1494. Selector.prototype = {
  1495. initialize: function(expression) {
  1496. this.params = {classNames: []};
  1497. this.expression = expression.toString().strip();
  1498. this.parseExpression();
  1499. this.compileMatcher();
  1500. },
  1501. parseExpression: function() {
  1502. function abort(message) { throw 'Parse error in selector: ' + message; }
  1503. if (this.expression == '') abort('empty expression');
  1504. var params = this.params, expr = this.expression, match, modifier, clause, rest;
  1505. while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) {
  1506. params.attributes = params.attributes || [];
  1507. params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''});
  1508. expr = match[1];
  1509. }
  1510. if (expr == '*') return this.params.wildcard = true;
  1511. while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) {
  1512. modifier = match[1], clause = match[2], rest = match[3];
  1513. switch (modifier) {
  1514. case '#': params.id = clause; break;
  1515. case '.': params.classNames.push(clause); break;
  1516. case '':
  1517. case undefined: params.tagName = clause.toUpperCase(); break;
  1518. default: abort(expr.inspect());
  1519. }
  1520. expr = rest;
  1521. }
  1522. if (expr.length > 0) abort(expr.inspect());
  1523. },
  1524. buildMatchExpression: function() {
  1525. var params = this.params, conditions = [], clause;
  1526. if (params.wildcard)
  1527. conditions.push('true');
  1528. if (clause = params.id)
  1529. conditions.push('element.readAttribute("id") == ' + clause.inspect());
  1530. if (clause = params.tagName)
  1531. conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
  1532. if ((clause = params.classNames).length > 0)
  1533. for (var i = 0, length = clause.length; i < length; i++)
  1534. conditions.push('element.hasClassName(' + clause[i].inspect() + ')');
  1535. if (clause = params.attributes) {
  1536. clause.each(function(attribute) {
  1537. var value = 'element.readAttribute(' + attribute.name.inspect() + ')';
  1538. var splitValueBy = function(delimiter) {
  1539. return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
  1540. }
  1541. switch (attribute.operator) {
  1542. case '=': conditions.push(value + ' == ' + attribute.value.inspect()); break;
  1543. case '~=': conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break;
  1544. case '|=': conditions.push(
  1545. splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect()
  1546. ); break;
  1547. case '!=': conditions.push(value + ' != ' + attribute.value.inspect()); break;
  1548. case '':
  1549. case undefined: conditions.push('element.hasAttribute(' + attribute.name.inspect() + ')'); break;
  1550. default: throw 'Unknown operator ' + attribute.operator + ' in selector';
  1551. }
  1552. });
  1553. }
  1554. return conditions.join(' && ');
  1555. },
  1556. compileMatcher: function() {
  1557. this.match = new Function('element', 'if (!element.tagName) return false; \
  1558. element = $(element); \
  1559. return ' + this.buildMatchExpression());
  1560. },
  1561. findElements: function(scope) {
  1562. var element;
  1563. if (element = $(this.params.id))
  1564. if (this.match(element))
  1565. if (!scope || Element.childOf(element, scope))
  1566. return [element];
  1567. scope = (scope || document).getElementsByTagName(this.params.tagName || '*');
  1568. var results = [];
  1569. for (var i = 0, length = scope.length; i < length; i++)
  1570. if (this.match(element = scope[i]))
  1571. results.push(Element.extend(element));
  1572. return results;
  1573. },
  1574. toString: function() {
  1575. return this.expression;
  1576. }
  1577. }
  1578. Object.extend(Selector, {
  1579. matchElements: function(elements, expression) {
  1580. var selector = new Selector(expression);
  1581. return elements.select(selector.match.bind(selector)).map(Element.extend);
  1582. },
  1583. findElement: function(elements, expression, index) {
  1584. if (typeof expression == 'number') index = expression, expression = false;
  1585. return Selector.matchElements(elements, expression || '*')[index || 0];
  1586. },
  1587. findChildElements: function(element, expressions) {
  1588. return expressions.map(function(expression) {
  1589. return expression.match(/[^\s"]+(?:"[^"]*"[^\s"]+)*/g).inject([null], function(results, expr) {
  1590. var selector = new Selector(expr);
  1591. return results.inject([], function(elements, result) {
  1592. return elements.concat(selector.findElements(result || element));
  1593. });
  1594. });
  1595. }).flatten();
  1596. }
  1597. });
  1598. function $$() {
  1599. return Selector.findChildElements(document, $A(arguments));
  1600. }
  1601. var Form = {
  1602. reset: function(form) {
  1603. $(form).reset();
  1604. return form;
  1605. },
  1606. serializeElements: function(elements, getHash) {
  1607. var data = elements.inject({}, function(result, element) {
  1608. if (!element.disabled && element.name) {
  1609. var key = element.name, value = $(element).getValue();
  1610. if (value != undefined) {
  1611. if (result[key]) {
  1612. if (result[key].constructor != Array) result[key] = [result[key]];
  1613. result[key].push(value);
  1614. }
  1615. else result[key] = value;
  1616. }
  1617. }
  1618. return result;
  1619. });
  1620. return getHash ? data : Hash.toQueryString(data);
  1621. }
  1622. };
  1623. Form.Methods = {
  1624. serialize: function(form, getHash) {
  1625. return Form.serializeElements(Form.getElements(form), getHash);
  1626. },
  1627. getElements: function(form) {
  1628. return $A($(form).getElementsByTagName('*')).inject([],
  1629. function(elements, child) {
  1630. if (Form.Element.Serializers[child.tagName.toLowerCase()])
  1631. elements.push(Element.extend(child));
  1632. return elements;
  1633. }
  1634. );
  1635. },
  1636. getInputs: function(form, typeName, name) {
  1637. form = $(form);
  1638. var inputs = form.getElementsByTagName('input');
  1639. if (!typeName && !name) return $A(inputs).map(Element.extend);
  1640. for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
  1641. var input = inputs[i];
  1642. if ((typeName && input.type != typeName) || (name && input.name != name))
  1643. continue;
  1644. matchingInputs.push(Element.extend(input));
  1645. }
  1646. return matchingInputs;
  1647. },
  1648. disable: function(form) {
  1649. form = $(form);
  1650. form.getElements().each(function(element) {
  1651. element.blur();
  1652. element.disabled = 'true';
  1653. });
  1654. return form;
  1655. },
  1656. enable: function(form) {
  1657. form = $(form);
  1658. form.getElements().each(function(element) {
  1659. element.disabled = '';
  1660. });
  1661. return form;
  1662. },
  1663. findFirstElement: function(form) {
  1664. return $(form).getElements().find(function(element) {
  1665. return element.type != 'hidden' && !element.disabled &&
  1666. ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
  1667. });
  1668. },
  1669. focusFirstElement: function(form) {
  1670. form = $(form);
  1671. form.findFirstElement().activate();
  1672. return form;
  1673. }
  1674. }
  1675. Object.extend(Form, Form.Methods);
  1676. /*--------------------------------------------------------------------------*/
  1677. Form.Element = {
  1678. focus: function(element) {
  1679. $(element).focus();
  1680. return element;
  1681. },
  1682. select: function(element) {
  1683. $(element).select();
  1684. return element;
  1685. }
  1686. }
  1687. Form.Element.Methods = {
  1688. serialize: function(element) {
  1689. element = $(element);
  1690. if (!element.disabled && element.name) {
  1691. var value = element.getValue();
  1692. if (value != undefined) {
  1693. var pair = {};
  1694. pair[element.name] = value;
  1695. return Hash.toQueryString(pair);
  1696. }
  1697. }
  1698. return '';
  1699. },
  1700. getValue: function(element) {
  1701. element = $(element);
  1702. var method = element.tagName.toLowerCase();
  1703. return Form.Element.Serializers[method](element);
  1704. },
  1705. clear: function(element) {
  1706. $(element).value = '';
  1707. return element;
  1708. },
  1709. present: function(element) {
  1710. return $(element).value != '';
  1711. },
  1712. activate: function(element) {
  1713. element = $(element);
  1714. element.focus();
  1715. if (element.select && ( element.tagName.toLowerCase() != 'input' ||
  1716. !['button', 'reset', 'submit'].include(element.type) ) )
  1717. element.select();
  1718. return element;
  1719. },
  1720. disable: function(element) {
  1721. element = $(element);
  1722. element.disabled = true;
  1723. return element;
  1724. },
  1725. enable: function(element) {
  1726. element = $(element);
  1727. element.blur();
  1728. element.disabled = false;
  1729. return element;
  1730. }
  1731. }
  1732. Object.extend(Form.Element, Form.Element.Methods);
  1733. var Field = Form.Element;
  1734. var $F = Form.Element.getValue;
  1735. /*--------------------------------------------------------------------------*/
  1736. Form.Element.Serializers = {
  1737. input: function(element) {
  1738. switch (element.type.toLowerCase()) {
  1739. case 'checkbox':
  1740. case 'radio':
  1741. return Form.Element.Serializers.inputSelector(element);
  1742. default:
  1743. return Form.Element.Serializers.textarea(element);
  1744. }
  1745. },
  1746. inputSelector: function(element) {
  1747. return element.checked ? element.value : null;
  1748. },
  1749. textarea: function(element) {
  1750. return element.value;
  1751. },
  1752. select: function(element) {
  1753. return this[element.type == 'select-one' ?
  1754. 'selectOne' : 'selectMany'](element);
  1755. },
  1756. selectOne: function(element) {
  1757. var index = element.selectedIndex;
  1758. return index >= 0 ? this.optionValue(element.options[index]) : null;
  1759. },
  1760. selectMany: function(element) {
  1761. var values, length = element.length;
  1762. if (!length) return null;
  1763. for (var i = 0, values = []; i < length; i++) {
  1764. var opt = element.options[i];
  1765. if (opt.selected) values.push(this.optionValue(opt));
  1766. }
  1767. return values;
  1768. },
  1769. optionValue: function(opt) {
  1770. // extend element because hasAttribute may not be native
  1771. return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  1772. }
  1773. }
  1774. /*--------------------------------------------------------------------------*/
  1775. Abstract.TimedObserver = function() {}
  1776. Abstract.TimedObserver.prototype = {
  1777. initialize: function(element, frequency, callback) {
  1778. this.frequency = frequency;
  1779. this.element = $(element);
  1780. this.callback = callback;
  1781. this.lastValue = this.getValue();
  1782. this.registerCallback();
  1783. },
  1784. registerCallback: function() {
  1785. setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  1786. },
  1787. onTimerEvent: function() {
  1788. var value = this.getValue();
  1789. var changed = ('string' == typeof this.lastValue && 'string' == typeof value
  1790. ? this.lastValue != value : String(this.lastValue) != String(value));
  1791. if (changed) {
  1792. this.callback(this.element, value);
  1793. this.lastValue = value;
  1794. }
  1795. }
  1796. }
  1797. Form.Element.Observer = Class.create();
  1798. Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  1799. getValue: function() {
  1800. return Form.Element.getValue(this.element);
  1801. }
  1802. });
  1803. Form.Observer = Class.create();
  1804. Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  1805. getValue: function() {
  1806. return Form.serialize(this.element);
  1807. }
  1808. });
  1809. /*--------------------------------------------------------------------------*/
  1810. Abstract.EventObserver = function() {}
  1811. Abstract.EventObserver.prototype = {
  1812. initialize: function(element, callback) {
  1813. this.element = $(element);
  1814. this.callback = callback;
  1815. this.lastValue = this.getValue();
  1816. if (this.element.tagName.toLowerCase() == 'form')
  1817. this.registerFormCallbacks();
  1818. else
  1819. this.registerCallback(this.element);
  1820. },
  1821. onElementEvent: function() {
  1822. var value = this.getValue();
  1823. if (this.lastValue != value) {
  1824. this.callback(this.element, value);
  1825. this.lastValue = value;
  1826. }
  1827. },
  1828. registerFormCallbacks: function() {
  1829. Form.getElements(this.element).each(this.registerCallback.bind(this));
  1830. },
  1831. registerCallback: function(element) {
  1832. if (element.type) {
  1833. switch (element.type.toLowerCase()) {
  1834. case 'checkbox':
  1835. case 'radio':
  1836. Event.observe(element, 'click', this.onElementEvent.bind(this));
  1837. break;
  1838. default:
  1839. Event.observe(element, 'change', this.onElementEvent.bind(this));
  1840. break;
  1841. }
  1842. }
  1843. }
  1844. }
  1845. Form.Element.EventObserver = Class.create();
  1846. Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  1847. getValue: function() {
  1848. return Form.Element.getValue(this.element);
  1849. }
  1850. });
  1851. Form.EventObserver = Class.create();
  1852. Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  1853. getValue: function() {
  1854. return Form.serialize(this.element);
  1855. }
  1856. });
  1857. if (!window.Event) {
  1858. var Event = new Object();
  1859. }
  1860. Object.extend(Event, {
  1861. KEY_BACKSPACE: 8,
  1862. KEY_TAB: 9,
  1863. KEY_RETURN: 13,
  1864. KEY_ESC: 27,
  1865. KEY_LEFT: 37,
  1866. KEY_UP: 38,
  1867. KEY_RIGHT: 39,
  1868. KEY_DOWN: 40,
  1869. KEY_DELETE: 46,
  1870. KEY_HOME: 36,
  1871. KEY_END: 35,
  1872. KEY_PAGEUP: 33,
  1873. KEY_PAGEDOWN: 34,
  1874. element: function(event) {
  1875. return event.target || event.srcElement;
  1876. },
  1877. isLeftClick: function(event) {
  1878. return (((event.which) && (event.which == 1)) ||
  1879. ((event.button) && (event.button == 1)));
  1880. },
  1881. pointerX: function(event) {
  1882. return event.pageX || (event.clientX +
  1883. (document.documentElement.scrollLeft || document.body.scrollLeft));
  1884. },
  1885. pointerY: function(event) {
  1886. return event.pageY || (event.clientY +
  1887. (document.documentElement.scrollTop || document.body.scrollTop));
  1888. },
  1889. stop: function(event) {
  1890. if (event.preventDefault) {
  1891. event.preventDefault();
  1892. event.stopPropagation();
  1893. } else {
  1894. event.returnValue = false;
  1895. event.cancelBubble = true;
  1896. }
  1897. },
  1898. // find the first node with the given tagName, starting from the
  1899. // node the event was triggered on; traverses the DOM upwards
  1900. findElement: function(event, tagName) {
  1901. var element = Event.element(event);
  1902. while (element.parentNode && (!element.tagName ||
  1903. (element.tagName.toUpperCase() != tagName.toUpperCase())))
  1904. element = element.parentNode;
  1905. return element;
  1906. },
  1907. observers: false,
  1908. _observeAndCache: function(element, name, observer, useCapture) {
  1909. if (!this.observers) this.observers = [];
  1910. if (element.addEventListener) {
  1911. this.observers.push([element, name, observer, useCapture]);
  1912. element.addEventListener(name, observer, useCapture);
  1913. } else if (element.attachEvent) {
  1914. this.observers.push([element, name, observer, useCapture]);
  1915. element.attachEvent('on' + name, observer);
  1916. }
  1917. },
  1918. unloadCache: function() {
  1919. if (!Event.observers) return;
  1920. for (var i = 0, length = Event.observers.length; i < length; i++) {
  1921. Event.stopObserving.apply(this, Event.observers[i]);
  1922. Event.observers[i][0] = null;
  1923. }
  1924. Event.observers = false;
  1925. },
  1926. observe: function(element, name, observer, useCapture) {
  1927. element = $(element);
  1928. useCapture = useCapture || false;
  1929. if (name == 'keypress' &&
  1930. (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
  1931. || element.attachEvent))
  1932. name = 'keydown';
  1933. Event._observeAndCache(element, name, observer, useCapture);
  1934. },
  1935. stopObserving: function(element, name, observer, useCapture) {
  1936. element = $(element);
  1937. useCapture = useCapture || false;
  1938. if (name == 'keypress' &&
  1939. (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
  1940. || element.detachEvent))
  1941. name = 'keydown';
  1942. if (element.removeEventListener) {
  1943. element.removeEventListener(name, observer, useCapture);
  1944. } else if (element.detachEvent) {
  1945. try {
  1946. element.detachEvent('on' + name, observer);
  1947. } catch (e) {}
  1948. }
  1949. }
  1950. });
  1951. /* prevent memory leaks in IE */
  1952. if (navigator.appVersion.match(/\bMSIE\b/))
  1953. Event.observe(window, 'unload', Event.unloadCache, false);
  1954. var Position = {
  1955. // set to true if needed, warning: firefox performance problems
  1956. // NOT neeeded for page scrolling, only if draggable contained in
  1957. // scrollable elements
  1958. includeScrollOffsets: false,
  1959. // must be called before calling withinIncludingScrolloffset, every time the
  1960. // page is scrolled
  1961. prepare: function() {
  1962. this.deltaX = window.pageXOffset
  1963. || document.documentElement.scrollLeft
  1964. || document.body.scrollLeft
  1965. || 0;
  1966. this.deltaY = window.pageYOffset
  1967. || document.documentElement.scrollTop
  1968. || document.body.scrollTop
  1969. || 0;
  1970. },
  1971. realOffset: function(element) {
  1972. var valueT = 0, valueL = 0;
  1973. do {
  1974. valueT += element.scrollTop || 0;
  1975. valueL += element.scrollLeft || 0;
  1976. element = element.parentNode;
  1977. } while (element);
  1978. return [valueL, valueT];
  1979. },
  1980. cumulativeOffset: function(element) {
  1981. var valueT = 0, valueL = 0;
  1982. do {
  1983. valueT += element.offsetTop || 0;
  1984. valueL += element.offsetLeft || 0;
  1985. element = element.offsetParent;
  1986. } while (element);
  1987. return [valueL, valueT];
  1988. },
  1989. positionedOffset: function(element) {
  1990. var valueT = 0, valueL = 0;
  1991. do {
  1992. valueT += element.offsetTop || 0;
  1993. valueL += element.offsetLeft || 0;
  1994. element = element.offsetParent;
  1995. if (element) {
  1996. if(element.tagName=='BODY') break;
  1997. var p = Element.getStyle(element, 'position');
  1998. if (p == 'relative' || p == 'absolute') break;
  1999. }
  2000. } while (element);
  2001. return [valueL, valueT];
  2002. },
  2003. offsetParent: function(element) {
  2004. if (element.offsetParent) return element.offsetParent;
  2005. if (element == document.body) return element;
  2006. while ((element = element.parentNode) && element != document.body)
  2007. if (Element.getStyle(element, 'position') != 'static')
  2008. return element;
  2009. return document.body;
  2010. },
  2011. // caches x/y coordinate pair to use with overlap
  2012. within: function(element, x, y) {
  2013. if (this.includeScrollOffsets)
  2014. return this.withinIncludingScrolloffsets(element, x, y);
  2015. this.xcomp = x;
  2016. this.ycomp = y;
  2017. this.offset = this.cumulativeOffset(element);
  2018. return (y >= this.offset[1] &&
  2019. y < this.offset[1] + element.offsetHeight &&
  2020. x >= this.offset[0] &&
  2021. x < this.offset[0] + element.offsetWidth);
  2022. },
  2023. withinIncludingScrolloffsets: function(element, x, y) {
  2024. var offsetcache = this.realOffset(element);
  2025. this.xcomp = x + offsetcache[0] - this.deltaX;
  2026. this.ycomp = y + offsetcache[1] - this.deltaY;
  2027. this.offset = this.cumulativeOffset(element);
  2028. return (this.ycomp >= this.offset[1] &&
  2029. this.ycomp < this.offset[1] + element.offsetHeight &&
  2030. this.xcomp >= this.offset[0] &&
  2031. this.xcomp < this.offset[0] + element.offsetWidth);
  2032. },
  2033. // within must be called directly before
  2034. overlap: function(mode, element) {
  2035. if (!mode) return 0;
  2036. if (mode == 'vertical')
  2037. return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
  2038. element.offsetHeight;
  2039. if (mode == 'horizontal')
  2040. return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
  2041. element.offsetWidth;
  2042. },
  2043. page: function(forElement) {
  2044. var valueT = 0, valueL = 0;
  2045. var element = forElement;
  2046. do {
  2047. valueT += element.offsetTop || 0;
  2048. valueL += element.offsetLeft || 0;
  2049. // Safari fix
  2050. if (element.offsetParent==document.body)
  2051. if (Element.getStyle(element,'position')=='absolute') break;
  2052. } while (element = element.offsetParent);
  2053. element = forElement;
  2054. do {
  2055. if (!window.opera || element.tagName=='BODY') {
  2056. valueT -= element.scrollTop || 0;
  2057. valueL -= element.scrollLeft || 0;
  2058. }
  2059. } while (element = element.parentNode);
  2060. return [valueL, valueT];
  2061. },
  2062. clone: function(source, target) {
  2063. var options = Object.extend({
  2064. setLeft: true,
  2065. setTop: true,
  2066. setWidth: true,
  2067. setHeight: true,
  2068. offsetTop: 0,
  2069. offsetLeft: 0
  2070. }, arguments[2] || {})
  2071. // find page position of source
  2072. source = $(source);
  2073. var p = Position.page(source);
  2074. // find coordinate system to use
  2075. target = $(target);
  2076. var delta = [0, 0];
  2077. var parent = null;
  2078. // delta [0,0] will do fine with position: fixed elements,
  2079. // position:absolute needs offsetParent deltas
  2080. if (Element.getStyle(target,'position') == 'absolute') {
  2081. parent = Position.offsetParent(target);
  2082. delta = Position.page(parent);
  2083. }
  2084. // correct by body offsets (fixes Safari)
  2085. if (parent == document.body) {
  2086. delta[0] -= document.body.offsetLeft;
  2087. delta[1] -= document.body.offsetTop;
  2088. }
  2089. // set position
  2090. if(options.setLeft) target.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
  2091. if(options.setTop) target.style.top = (p[1] - delta[1] + options.offsetTop) + 'px';
  2092. if(options.setWidth) target.style.width = source.offsetWidth + 'px';
  2093. if(options.setHeight) target.style.height = source.offsetHeight + 'px';
  2094. },
  2095. absolutize: function(element) {
  2096. element = $(element);
  2097. if (element.style.position == 'absolute') return;
  2098. Position.prepare();
  2099. var offsets = Position.positionedOffset(element);
  2100. var top = offsets[1];
  2101. var left = offsets[0];
  2102. var width = element.clientWidth;
  2103. var height = element.clientHeight;
  2104. element._originalLeft = left - parseFloat(element.style.left || 0);
  2105. element._originalTop = top - parseFloat(element.style.top || 0);
  2106. element._originalWidth = element.style.width;
  2107. element._originalHeight = element.style.height;
  2108. element.style.position = 'absolute';
  2109. element.style.top = top + 'px';
  2110. element.style.left = left + 'px';
  2111. element.style.width = width + 'px';
  2112. element.style.height = height + 'px';
  2113. },
  2114. relativize: function(element) {
  2115. element = $(element);
  2116. if (element.style.position == 'relative') return;
  2117. Position.prepare();
  2118. element.style.position = 'relative';
  2119. var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
  2120. var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
  2121. element.style.top = top + 'px';
  2122. element.style.left = left + 'px';
  2123. element.style.height = element._originalHeight;
  2124. element.style.width = element._originalWidth;
  2125. }
  2126. }
  2127. // Safari returns margins on body which is incorrect if the child is absolutely
  2128. // positioned. For performance reasons, redefine Position.cumulativeOffset for
  2129. // KHTML/WebKit only.
  2130. if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  2131. Position.cumulativeOffset = function(element) {
  2132. var valueT = 0, valueL = 0;
  2133. do {
  2134. valueT += element.offsetTop || 0;
  2135. valueL += element.offsetLeft || 0;
  2136. if (element.offsetParent == document.body)
  2137. if (Element.getStyle(element, 'position') == 'absolute') break;
  2138. element = element.offsetParent;
  2139. } while (element);
  2140. return [valueL, valueT];
  2141. }
  2142. }
  2143. Element.addMethods();
  2144. // ------------------------------------------------------------------------
  2145. // ------------------------------------------------------------------------
  2146. // The rest of this file is the actual ray tracer written by Adam
  2147. // Burmister. It's a concatenation of the following files:
  2148. //
  2149. // flog/color.js
  2150. // flog/light.js
  2151. // flog/vector.js
  2152. // flog/ray.js
  2153. // flog/scene.js
  2154. // flog/material/basematerial.js
  2155. // flog/material/solid.js
  2156. // flog/material/chessboard.js
  2157. // flog/shape/baseshape.js
  2158. // flog/shape/sphere.js
  2159. // flog/shape/plane.js
  2160. // flog/intersectioninfo.js
  2161. // flog/camera.js
  2162. // flog/background.js
  2163. // flog/engine.js
  2164. /* Fake a Flog.* namespace */
  2165. if(typeof(Flog) == 'undefined') var Flog = {};
  2166. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  2167. Flog.RayTracer.Color = Class.create();
  2168. Flog.RayTracer.Color.prototype = {
  2169. red : 0.0,
  2170. green : 0.0,
  2171. blue : 0.0,
  2172. initialize : function(r, g, b) {
  2173. if(!r) r = 0.0;
  2174. if(!g) g = 0.0;
  2175. if(!b) b = 0.0;
  2176. this.red = r;
  2177. this.green = g;
  2178. this.blue = b;
  2179. },
  2180. add : function(c1, c2){
  2181. var result = new Flog.RayTracer.Color(0,0,0);
  2182. result.red = c1.red + c2.red;
  2183. result.green = c1.green + c2.green;
  2184. result.blue = c1.blue + c2.blue;
  2185. return result;
  2186. },
  2187. addScalar: function(c1, s){
  2188. var result = new Flog.RayTracer.Color(0,0,0);
  2189. result.red = c1.red + s;
  2190. result.green = c1.green + s;
  2191. result.blue = c1.blue + s;
  2192. result.limit();
  2193. return result;
  2194. },
  2195. subtract: function(c1, c2){
  2196. var result = new Flog.RayTracer.Color(0,0,0);
  2197. result.red = c1.red - c2.red;
  2198. result.green = c1.green - c2.green;
  2199. result.blue = c1.blue - c2.blue;
  2200. return result;
  2201. },
  2202. multiply : function(c1, c2) {
  2203. var result = new Flog.RayTracer.Color(0,0,0);
  2204. result.red = c1.red * c2.red;
  2205. result.green = c1.green * c2.green;
  2206. result.blue = c1.blue * c2.blue;
  2207. return result;
  2208. },
  2209. multiplyScalar : function(c1, f) {
  2210. var result = new Flog.RayTracer.Color(0,0,0);
  2211. result.red = c1.red * f;
  2212. result.green = c1.green * f;
  2213. result.blue = c1.blue * f;
  2214. return result;
  2215. },
  2216. divideFactor : function(c1, f) {
  2217. var result = new Flog.RayTracer.Color(0,0,0);
  2218. result.red = c1.red / f;
  2219. result.green = c1.green / f;
  2220. result.blue = c1.blue / f;
  2221. return result;
  2222. },
  2223. limit: function(){
  2224. this.red = (this.red > 0.0) ? ( (this.red > 1.0) ? 1.0 : this.red ) : 0.0;
  2225. this.green = (this.green > 0.0) ? ( (this.green > 1.0) ? 1.0 : this.green ) : 0.0;
  2226. this.blue = (this.blue > 0.0) ? ( (this.blue > 1.0) ? 1.0 : this.blue ) : 0.0;
  2227. },
  2228. distance : function(color) {
  2229. var d = Math.abs(this.red - color.red) + Math.abs(this.green - color.green) + Math.abs(this.blue - color.blue);
  2230. return d;
  2231. },
  2232. blend: function(c1, c2, w){
  2233. var result = new Flog.RayTracer.Color(0,0,0);
  2234. result = Flog.RayTracer.Color.prototype.add(
  2235. Flog.RayTracer.Color.prototype.multiplyScalar(c1, 1 - w),
  2236. Flog.RayTracer.Color.prototype.multiplyScalar(c2, w)
  2237. );
  2238. return result;
  2239. },
  2240. toString : function () {
  2241. var r = Math.floor(this.red*255);
  2242. var g = Math.floor(this.green*255);
  2243. var b = Math.floor(this.blue*255);
  2244. return "rgb("+ r +","+ g +","+ b +")";
  2245. }
  2246. }
  2247. /* Fake a Flog.* namespace */
  2248. if(typeof(Flog) == 'undefined') var Flog = {};
  2249. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  2250. Flog.RayTracer.Light = Class.create();
  2251. Flog.RayTracer.Light.prototype = {
  2252. position: null,
  2253. color: null,
  2254. intensity: 10.0,
  2255. initialize : function(pos, color, intensity) {
  2256. this.position = pos;
  2257. this.color = color;
  2258. this.intensity = (intensity ? intensity : 10.0);
  2259. },
  2260. getIntensity: function(distance){
  2261. if(distance >= intensity) return 0;
  2262. return Math.pow((intensity - distance) / strength, 0.2);
  2263. },
  2264. toString : function () {
  2265. return 'Light [' + this.position.x + ',' + this.position.y + ',' + this.position.z + ']';
  2266. }
  2267. }
  2268. /* Fake a Flog.* namespace */
  2269. if(typeof(Flog) == 'undefined') var Flog = {};
  2270. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  2271. Flog.RayTracer.Vector = Class.create();
  2272. Flog.RayTracer.Vector.prototype = {
  2273. x : 0.0,
  2274. y : 0.0,
  2275. z : 0.0,
  2276. initialize : function(x, y, z) {
  2277. this.x = (x ? x : 0);
  2278. this.y = (y ? y : 0);
  2279. this.z = (z ? z : 0);
  2280. },
  2281. copy: function(vector){
  2282. this.x = vector.x;
  2283. this.y = vector.y;
  2284. this.z = vector.z;
  2285. },
  2286. normalize : function() {
  2287. var m = this.magnitude();
  2288. return new Flog.RayTracer.Vector(this.x / m, this.y / m, this.z / m);
  2289. },
  2290. magnitude : function() {
  2291. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z));
  2292. },
  2293. cross : function(w) {
  2294. return new Flog.RayTracer.Vector(
  2295. -this.z * w.y + this.y * w.z,
  2296. this.z * w.x - this.x * w.z,
  2297. -this.y * w.x + this.x * w.y);
  2298. },
  2299. dot : function(w) {
  2300. return this.x * w.x + this.y * w.y + this.z * w.z;
  2301. },
  2302. add : function(v, w) {
  2303. return new Flog.RayTracer.Vector(w.x + v.x, w.y + v.y, w.z + v.z);
  2304. },
  2305. subtract : function(v, w) {
  2306. if(!w || !v) throw 'Vectors must be defined [' + v + ',' + w + ']';
  2307. return new Flog.RayTracer.Vector(v.x - w.x, v.y - w.y, v.z - w.z);
  2308. },
  2309. multiplyVector : function(v, w) {
  2310. return new Flog.RayTracer.Vector(v.x * w.x, v.y * w.y, v.z * w.z);
  2311. },
  2312. multiplyScalar : function(v, w) {
  2313. return new Flog.RayTracer.Vector(v.x * w, v.y * w, v.z * w);
  2314. },
  2315. toString : function () {
  2316. return 'Vector [' + this.x + ',' + this.y + ',' + this.z + ']';
  2317. }
  2318. }
  2319. /* Fake a Flog.* namespace */
  2320. if(typeof(Flog) == 'undefined') var Flog = {};
  2321. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  2322. Flog.RayTracer.Ray = Class.create();
  2323. Flog.RayTracer.Ray.prototype = {
  2324. position : null,
  2325. direction : null,
  2326. initialize : function(pos, dir) {
  2327. this.position = pos;
  2328. this.direction = dir;
  2329. },
  2330. toString : function () {
  2331. return 'Ray [' + this.position + ',' + this.direction + ']';
  2332. }
  2333. }
  2334. /* Fake a Flog.* namespace */
  2335. if(typeof(Flog) == 'undefined') var Flog = {};
  2336. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  2337. Flog.RayTracer.Scene = Class.create();
  2338. Flog.RayTracer.Scene.prototype = {
  2339. camera : null,
  2340. shapes : [],
  2341. lights : [],
  2342. background : null,
  2343. initialize : function() {
  2344. this.camera = new Flog.RayTracer.Camera(
  2345. new Flog.RayTracer.Vector(0,0,-5),
  2346. new Flog.RayTracer.Vector(0,0,1),
  2347. new Flog.RayTracer.Vector(0,1,0)
  2348. );
  2349. this.shapes = new Array();
  2350. this.lights = new Array();
  2351. this.background = new Flog.RayTracer.Background(new Flog.RayTracer.Color(0,0,0.5), 0.2);
  2352. }
  2353. }
  2354. /* Fake a Flog.* namespace */
  2355. if(typeof(Flog) == 'undefined') var Flog = {};
  2356. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  2357. if(typeof(Flog.RayTracer.Material) == 'undefined') Flog.RayTracer.Material = {};
  2358. Flog.RayTracer.Material.BaseMaterial = Class.create();
  2359. Flog.RayTracer.Material.BaseMaterial.prototype = {
  2360. gloss: 2.0, // [0...infinity] 0 = matt
  2361. transparency: 0.0, // 0=opaque
  2362. reflection: 0.0, // [0...infinity] 0 = no reflection
  2363. refraction: 0.50,
  2364. hasTexture: false,
  2365. initialize : function() {
  2366. },
  2367. getColor: function(u, v){
  2368. },
  2369. wrapUp: function(t){
  2370. t = t % 2.0;
  2371. if(t < -1) t += 2.0;
  2372. if(t >= 1) t -= 2.0;
  2373. return t;
  2374. },
  2375. toString : function () {
  2376. return 'Material [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']';
  2377. }
  2378. }
  2379. /* Fake a Flog.* namespace */
  2380. if(typeof(Flog) == 'undefined') var Flog = {};
  2381. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  2382. Flog.RayTracer.Material.Solid = Class.create();
  2383. Flog.RayTracer.Material.Solid.prototype = Object.extend(
  2384. new Flog.RayTracer.Material.BaseMaterial(), {
  2385. initialize : function(color, reflection, refraction, transparency, gloss) {
  2386. this.color = color;
  2387. this.reflection = reflection;
  2388. this.transparency = transparency;
  2389. this.gloss = gloss;
  2390. this.hasTexture = false;
  2391. },
  2392. getColor: function(u, v){
  2393. return this.color;
  2394. },
  2395. toString : function () {
  2396. return 'SolidMaterial [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']';
  2397. }
  2398. }
  2399. );
  2400. /* Fake a Flog.* namespace */
  2401. if(typeof(Flog) == 'undefined') var Flog = {};
  2402. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  2403. Flog.RayTracer.Material.Chessboard = Class.create();
  2404. Flog.RayTracer.Material.Chessboard.prototype = Object.extend(
  2405. new Flog.RayTracer.Material.BaseMaterial(), {
  2406. colorEven: null,
  2407. colorOdd: null,
  2408. density: 0.5,
  2409. initialize : function(colorEven, colorOdd, reflection, transparency, gloss, density) {
  2410. this.colorEven = colorEven;
  2411. this.colorOdd = colorOdd;
  2412. this.reflection = reflection;
  2413. this.transparency = transparency;
  2414. this.gloss = gloss;
  2415. this.density = density;
  2416. this.hasTexture = true;
  2417. },
  2418. getColor: function(u, v){
  2419. var t = this.wrapUp(u * this.density) * this.wrapUp(v * this.density);
  2420. if(t < 0.0)
  2421. return this.colorEven;
  2422. else
  2423. return this.colorOdd;
  2424. },
  2425. toString : function () {
  2426. return 'ChessMaterial [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']';
  2427. }
  2428. }
  2429. );
  2430. /* Fake a Flog.* namespace */
  2431. if(typeof(Flog) == 'undefined') var Flog = {};
  2432. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  2433. if(typeof(Flog.RayTracer.Shape) == 'undefined') Flog.RayTracer.Shape = {};
  2434. Flog.RayTracer.Shape.BaseShape = Class.create();
  2435. Flog.RayTracer.Shape.BaseShape.prototype = {
  2436. position: null,
  2437. material: null,
  2438. initialize : function() {
  2439. this.position = new Vector(0,0,0);
  2440. this.material = new Flog.RayTracer.Material.SolidMaterial(
  2441. new Flog.RayTracer.Color(1,0,1),
  2442. 0,
  2443. 0,
  2444. 0
  2445. );
  2446. },
  2447. toString : function () {
  2448. return 'Material [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']';
  2449. }
  2450. }
  2451. /* Fake a Flog.* namespace */
  2452. if(typeof(Flog) == 'undefined') var Flog = {};
  2453. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  2454. if(typeof(Flog.RayTracer.Shape) == 'undefined') Flog.RayTracer.Shape = {};
  2455. Flog.RayTracer.Shape.Sphere = Class.create();
  2456. Flog.RayTracer.Shape.Sphere.prototype = {
  2457. initialize : function(pos, radius, material) {
  2458. this.radius = radius;
  2459. this.position = pos;
  2460. this.material = material;
  2461. },
  2462. intersect: function(ray){
  2463. var info = new Flog.RayTracer.IntersectionInfo();
  2464. info.shape = this;
  2465. var dst = Flog.RayTracer.Vector.prototype.subtract(ray.position, this.position);
  2466. var B = dst.dot(ray.direction);
  2467. var C = dst.dot(dst) - (this.radius * this.radius);
  2468. var D = (B * B) - C;
  2469. if(D > 0){ // intersection!
  2470. info.isHit = true;
  2471. info.distance = (-B) - Math.sqrt(D);
  2472. info.position = Flog.RayTracer.Vector.prototype.add(
  2473. ray.position,
  2474. Flog.RayTracer.Vector.prototype.multiplyScalar(
  2475. ray.direction,
  2476. info.distance
  2477. )
  2478. );
  2479. info.normal = Flog.RayTracer.Vector.prototype.subtract(
  2480. info.position,
  2481. this.position
  2482. ).normalize();
  2483. info.color = this.material.getColor(0,0);
  2484. } else {
  2485. info.isHit = false;
  2486. }
  2487. return info;
  2488. },
  2489. toString : function () {
  2490. return 'Sphere [position=' + this.position + ', radius=' + this.radius + ']';
  2491. }
  2492. }
  2493. /* Fake a Flog.* namespace */
  2494. if(typeof(Flog) == 'undefined') var Flog = {};
  2495. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  2496. if(typeof(Flog.RayTracer.Shape) == 'undefined') Flog.RayTracer.Shape = {};
  2497. Flog.RayTracer.Shape.Plane = Class.create();
  2498. Flog.RayTracer.Shape.Plane.prototype = {
  2499. d: 0.0,
  2500. initialize : function(pos, d, material) {
  2501. this.position = pos;
  2502. this.d = d;
  2503. this.material = material;
  2504. },
  2505. intersect: function(ray){
  2506. var info = new Flog.RayTracer.IntersectionInfo();
  2507. var Vd = this.position.dot(ray.direction);
  2508. if(Vd == 0) return info; // no intersection
  2509. var t = -(this.position.dot(ray.position) + this.d) / Vd;
  2510. if(t <= 0) return info;
  2511. info.shape = this;
  2512. info.isHit = true;
  2513. info.position = Flog.RayTracer.Vector.prototype.add(
  2514. ray.position,
  2515. Flog.RayTracer.Vector.prototype.multiplyScalar(
  2516. ray.direction,
  2517. t
  2518. )
  2519. );
  2520. info.normal = this.position;
  2521. info.distance = t;
  2522. if(this.material.hasTexture){
  2523. var vU = new Flog.RayTracer.Vector(this.position.y, this.position.z, -this.position.x);
  2524. var vV = vU.cross(this.position);
  2525. var u = info.position.dot(vU);
  2526. var v = info.position.dot(vV);
  2527. info.color = this.material.getColor(u,v);
  2528. } else {
  2529. info.color = this.material.getColor(0,0);
  2530. }
  2531. return info;
  2532. },
  2533. toString : function () {
  2534. return 'Plane [' + this.position + ', d=' + this.d + ']';
  2535. }
  2536. }
  2537. /* Fake a Flog.* namespace */
  2538. if(typeof(Flog) == 'undefined') var Flog = {};
  2539. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  2540. Flog.RayTracer.IntersectionInfo = Class.create();
  2541. Flog.RayTracer.IntersectionInfo.prototype = {
  2542. isHit: false,
  2543. hitCount: 0,
  2544. shape: null,
  2545. position: null,
  2546. normal: null,
  2547. color: null,
  2548. distance: null,
  2549. initialize : function() {
  2550. this.color = new Flog.RayTracer.Color(0,0,0);
  2551. },
  2552. toString : function () {
  2553. return 'Intersection [' + this.position + ']';
  2554. }
  2555. }
  2556. /* Fake a Flog.* namespace */
  2557. if(typeof(Flog) == 'undefined') var Flog = {};
  2558. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  2559. Flog.RayTracer.Camera = Class.create();
  2560. Flog.RayTracer.Camera.prototype = {
  2561. position: null,
  2562. lookAt: null,
  2563. equator: null,
  2564. up: null,
  2565. screen: null,
  2566. initialize : function(pos, lookAt, up) {
  2567. this.position = pos;
  2568. this.lookAt = lookAt;
  2569. this.up = up;
  2570. this.equator = lookAt.normalize().cross(this.up);
  2571. this.screen = Flog.RayTracer.Vector.prototype.add(this.position, this.lookAt);
  2572. },
  2573. getRay: function(vx, vy){
  2574. var pos = Flog.RayTracer.Vector.prototype.subtract(
  2575. this.screen,
  2576. Flog.RayTracer.Vector.prototype.subtract(
  2577. Flog.RayTracer.Vector.prototype.multiplyScalar(this.equator, vx),
  2578. Flog.RayTracer.Vector.prototype.multiplyScalar(this.up, vy)
  2579. )
  2580. );
  2581. pos.y = pos.y * -1;
  2582. var dir = Flog.RayTracer.Vector.prototype.subtract(
  2583. pos,
  2584. this.position
  2585. );
  2586. var ray = new Flog.RayTracer.Ray(pos, dir.normalize());
  2587. return ray;
  2588. },
  2589. toString : function () {
  2590. return 'Ray []';
  2591. }
  2592. }
  2593. /* Fake a Flog.* namespace */
  2594. if(typeof(Flog) == 'undefined') var Flog = {};
  2595. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  2596. Flog.RayTracer.Background = Class.create();
  2597. Flog.RayTracer.Background.prototype = {
  2598. color : null,
  2599. ambience : 0.0,
  2600. initialize : function(color, ambience) {
  2601. this.color = color;
  2602. this.ambience = ambience;
  2603. }
  2604. }
  2605. /* Fake a Flog.* namespace */
  2606. if(typeof(Flog) == 'undefined') var Flog = {};
  2607. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  2608. Flog.RayTracer.Engine = Class.create();
  2609. Flog.RayTracer.Engine.prototype = {
  2610. canvas: null, /* 2d context we can render to */
  2611. initialize: function(options){
  2612. this.options = Object.extend({
  2613. canvasHeight: 100,
  2614. canvasWidth: 100,
  2615. pixelWidth: 2,
  2616. pixelHeight: 2,
  2617. renderDiffuse: false,
  2618. renderShadows: false,
  2619. renderHighlights: false,
  2620. renderReflections: false,
  2621. rayDepth: 2
  2622. }, options || {});
  2623. this.options.canvasHeight /= this.options.pixelHeight;
  2624. this.options.canvasWidth /= this.options.pixelWidth;
  2625. /* TODO: dynamically include other scripts */
  2626. },
  2627. setPixel: function(x, y, color){
  2628. var pxW, pxH;
  2629. pxW = this.options.pixelWidth;
  2630. pxH = this.options.pixelHeight;
  2631. if (this.canvas) {
  2632. this.canvas.fillStyle = color.toString();
  2633. this.canvas.fillRect (x * pxW, y * pxH, pxW, pxH);
  2634. } else {
  2635. // print(x * pxW, y * pxH, pxW, pxH);
  2636. }
  2637. },
  2638. renderScene: function(scene, canvas){
  2639. /* Get canvas */
  2640. if (canvas) {
  2641. this.canvas = canvas.getContext("2d");
  2642. } else {
  2643. this.canvas = null;
  2644. }
  2645. var canvasHeight = this.options.canvasHeight;
  2646. var canvasWidth = this.options.canvasWidth;
  2647. for(var y=0; y < canvasHeight; y++){
  2648. for(var x=0; x < canvasWidth; x++){
  2649. var yp = y * 1.0 / canvasHeight * 2 - 1;
  2650. var xp = x * 1.0 / canvasWidth * 2 - 1;
  2651. var ray = scene.camera.getRay(xp, yp);
  2652. var color = this.getPixelColor(ray, scene);
  2653. this.setPixel(x, y, color);
  2654. }
  2655. }
  2656. },
  2657. getPixelColor: function(ray, scene){
  2658. var info = this.testIntersection(ray, scene, null);
  2659. if(info.isHit){
  2660. var color = this.rayTrace(info, ray, scene, 0);
  2661. return color;
  2662. }
  2663. return scene.background.color;
  2664. },
  2665. testIntersection: function(ray, scene, exclude){
  2666. var hits = 0;
  2667. var best = new Flog.RayTracer.IntersectionInfo();
  2668. best.distance = 2000;
  2669. for(var i=0; i<scene.shapes.length; i++){
  2670. var shape = scene.shapes[i];
  2671. if(shape != exclude){
  2672. var info = shape.intersect(ray);
  2673. if(info.isHit && info.distance >= 0 && info.distance < best.distance){
  2674. best = info;
  2675. hits++;
  2676. }
  2677. }
  2678. }
  2679. best.hitCount = hits;
  2680. return best;
  2681. },
  2682. getReflectionRay: function(P,N,V){
  2683. var c1 = -N.dot(V);
  2684. var R1 = Flog.RayTracer.Vector.prototype.add(
  2685. Flog.RayTracer.Vector.prototype.multiplyScalar(N, 2*c1),
  2686. V
  2687. );
  2688. return new Flog.RayTracer.Ray(P, R1);
  2689. },
  2690. rayTrace: function(info, ray, scene, depth){
  2691. // Calc ambient
  2692. var color = Flog.RayTracer.Color.prototype.multiplyScalar(info.color, scene.background.ambience);
  2693. var oldColor = color;
  2694. var shininess = Math.pow(10, info.shape.material.gloss + 1);
  2695. for(var i=0; i<scene.lights.length; i++){
  2696. var light = scene.lights[i];
  2697. // Calc diffuse lighting
  2698. var v = Flog.RayTracer.Vector.prototype.subtract(
  2699. light.position,
  2700. info.position
  2701. ).normalize();
  2702. if(this.options.renderDiffuse){
  2703. var L = v.dot(info.normal);
  2704. if(L > 0.0){
  2705. color = Flog.RayTracer.Color.prototype.add(
  2706. color,
  2707. Flog.RayTracer.Color.prototype.multiply(
  2708. info.color,
  2709. Flog.RayTracer.Color.prototype.multiplyScalar(
  2710. light.color,
  2711. L
  2712. )
  2713. )
  2714. );
  2715. }
  2716. }
  2717. // The greater the depth the more accurate the colours, but
  2718. // this is exponentially (!) expensive
  2719. if(depth <= this.options.rayDepth){
  2720. // calculate reflection ray
  2721. if(this.options.renderReflections && info.shape.material.reflection > 0)
  2722. {
  2723. var reflectionRay = this.getReflectionRay(info.position, info.normal, ray.direction);
  2724. var refl = this.testIntersection(reflectionRay, scene, info.shape);
  2725. if (refl.isHit && refl.distance > 0){
  2726. refl.color = this.rayTrace(refl, reflectionRay, scene, depth + 1);
  2727. } else {
  2728. refl.color = scene.background.color;
  2729. }
  2730. color = Flog.RayTracer.Color.prototype.blend(
  2731. color,
  2732. refl.color,
  2733. info.shape.material.reflection
  2734. );
  2735. }
  2736. // Refraction
  2737. /* TODO */
  2738. }
  2739. /* Render shadows and highlights */
  2740. var shadowInfo = new Flog.RayTracer.IntersectionInfo();
  2741. if(this.options.renderShadows){
  2742. var shadowRay = new Flog.RayTracer.Ray(info.position, v);
  2743. shadowInfo = this.testIntersection(shadowRay, scene, info.shape);
  2744. if(shadowInfo.isHit && shadowInfo.shape != info.shape /*&& shadowInfo.shape.type != 'PLANE'*/){
  2745. var vA = Flog.RayTracer.Color.prototype.multiplyScalar(color, 0.5);
  2746. var dB = (0.5 * Math.pow(shadowInfo.shape.material.transparency, 0.5));
  2747. color = Flog.RayTracer.Color.prototype.addScalar(vA,dB);
  2748. }
  2749. }
  2750. // Phong specular highlights
  2751. if(this.options.renderHighlights && !shadowInfo.isHit && info.shape.material.gloss > 0){
  2752. var Lv = Flog.RayTracer.Vector.prototype.subtract(
  2753. info.shape.position,
  2754. light.position
  2755. ).normalize();
  2756. var E = Flog.RayTracer.Vector.prototype.subtract(
  2757. scene.camera.position,
  2758. info.shape.position
  2759. ).normalize();
  2760. var H = Flog.RayTracer.Vector.prototype.subtract(
  2761. E,
  2762. Lv
  2763. ).normalize();
  2764. var glossWeight = Math.pow(Math.max(info.normal.dot(H), 0), shininess);
  2765. color = Flog.RayTracer.Color.prototype.add(
  2766. Flog.RayTracer.Color.prototype.multiplyScalar(light.color, glossWeight),
  2767. color
  2768. );
  2769. }
  2770. }
  2771. color.limit();
  2772. return color;
  2773. }
  2774. };
  2775. function renderScene(){
  2776. var scene = new Flog.RayTracer.Scene();
  2777. scene.camera = new Flog.RayTracer.Camera(
  2778. new Flog.RayTracer.Vector(0, 0, -15),
  2779. new Flog.RayTracer.Vector(-0.2, 0, 5),
  2780. new Flog.RayTracer.Vector(0, 1, 0)
  2781. );
  2782. scene.background = new Flog.RayTracer.Background(
  2783. new Flog.RayTracer.Color(0.5, 0.5, 0.5),
  2784. 0.4
  2785. );
  2786. var sphere = new Flog.RayTracer.Shape.Sphere(
  2787. new Flog.RayTracer.Vector(-1.5, 1.5, 2),
  2788. 1.5,
  2789. new Flog.RayTracer.Material.Solid(
  2790. new Flog.RayTracer.Color(0,0.5,0.5),
  2791. 0.3,
  2792. 0.0,
  2793. 0.0,
  2794. 2.0
  2795. )
  2796. );
  2797. var sphere1 = new Flog.RayTracer.Shape.Sphere(
  2798. new Flog.RayTracer.Vector(1, 0.25, 1),
  2799. 0.5,
  2800. new Flog.RayTracer.Material.Solid(
  2801. new Flog.RayTracer.Color(0.9,0.9,0.9),
  2802. 0.1,
  2803. 0.0,
  2804. 0.0,
  2805. 1.5
  2806. )
  2807. );
  2808. var plane = new Flog.RayTracer.Shape.Plane(
  2809. new Flog.RayTracer.Vector(0.1, 0.9, -0.5).normalize(),
  2810. 1.2,
  2811. new Flog.RayTracer.Material.Chessboard(
  2812. new Flog.RayTracer.Color(1,1,1),
  2813. new Flog.RayTracer.Color(0,0,0),
  2814. 0.2,
  2815. 0.0,
  2816. 1.0,
  2817. 0.7
  2818. )
  2819. );
  2820. scene.shapes.push(plane);
  2821. scene.shapes.push(sphere);
  2822. scene.shapes.push(sphere1);
  2823. var light = new Flog.RayTracer.Light(
  2824. new Flog.RayTracer.Vector(5, 10, -1),
  2825. new Flog.RayTracer.Color(0.8, 0.8, 0.8)
  2826. );
  2827. var light1 = new Flog.RayTracer.Light(
  2828. new Flog.RayTracer.Vector(-3, 5, -15),
  2829. new Flog.RayTracer.Color(0.8, 0.8, 0.8),
  2830. 100
  2831. );
  2832. scene.lights.push(light);
  2833. scene.lights.push(light1);
  2834. var imageWidth = 100; // $F('imageWidth');
  2835. var imageHeight = 100; // $F('imageHeight');
  2836. var pixelSize = "5,5".split(','); // $F('pixelSize').split(',');
  2837. var renderDiffuse = true; // $F('renderDiffuse');
  2838. var renderShadows = true; // $F('renderShadows');
  2839. var renderHighlights = true; // $F('renderHighlights');
  2840. var renderReflections = true; // $F('renderReflections');
  2841. var rayDepth = 2;//$F('rayDepth');
  2842. var raytracer = new Flog.RayTracer.Engine(
  2843. {
  2844. canvasWidth: imageWidth,
  2845. canvasHeight: imageHeight,
  2846. pixelWidth: pixelSize[0],
  2847. pixelHeight: pixelSize[1],
  2848. "renderDiffuse": renderDiffuse,
  2849. "renderHighlights": renderHighlights,
  2850. "renderShadows": renderShadows,
  2851. "renderReflections": renderReflections,
  2852. "rayDepth": rayDepth
  2853. }
  2854. );
  2855. raytracer.renderScene(scene, null, 0);
  2856. }