graphEditor.tsx 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. import * as React from "react";
  2. import { GlobalState } from './globalState';
  3. import { NodeMaterialBlock } from 'babylonjs/Materials/Node/nodeMaterialBlock';
  4. import { NodeListComponent } from './components/nodeList/nodeListComponent';
  5. import { PropertyTabComponent } from './components/propertyTab/propertyTabComponent';
  6. import { Portal } from './portal';
  7. import { LogComponent, LogEntry } from './components/log/logComponent';
  8. import { DataStorage } from 'babylonjs/Misc/dataStorage';
  9. import { NodeMaterialBlockConnectionPointTypes } from 'babylonjs/Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes';
  10. import { InputBlock } from 'babylonjs/Materials/Node/Blocks/Input/inputBlock';
  11. import { Nullable } from 'babylonjs/types';
  12. import { MessageDialogComponent } from './sharedComponents/messageDialog';
  13. import { BlockTools } from './blockTools';
  14. import { PreviewManager } from './components/preview/previewManager';
  15. import { IEditorData } from './nodeLocationInfo';
  16. import { PreviewMeshControlComponent } from './components/preview/previewMeshControlComponent';
  17. import { PreviewAreaComponent } from './components/preview/previewAreaComponent';
  18. import { SerializationTools } from './serializationTools';
  19. import { GraphCanvasComponent } from './diagram/graphCanvas';
  20. import { GraphNode } from './diagram/graphNode';
  21. import { GraphFrame } from './diagram/graphFrame';
  22. import * as ReactDOM from 'react-dom';
  23. import { IInspectorOptions } from "babylonjs/Debug/debugLayer";
  24. import { _TypeStore } from 'babylonjs/Misc/typeStore';
  25. require("./main.scss");
  26. interface IGraphEditorProps {
  27. globalState: GlobalState;
  28. }
  29. interface IGraphEditorState {
  30. showPreviewPopUp: boolean;
  31. };
  32. interface IInternalPreviewAreaOptions extends IInspectorOptions {
  33. popup: boolean;
  34. original: boolean;
  35. explorerWidth?: string;
  36. inspectorWidth?: string;
  37. embedHostWidth?: string;
  38. }
  39. export class GraphEditor extends React.Component<IGraphEditorProps, IGraphEditorState> {
  40. private readonly NodeWidth = 100;
  41. private _graphCanvas: GraphCanvasComponent;
  42. private _startX: number;
  43. private _moveInProgress: boolean;
  44. private _leftWidth = DataStorage.ReadNumber("LeftWidth", 200);
  45. private _rightWidth = DataStorage.ReadNumber("RightWidth", 300);
  46. private _blocks = new Array<NodeMaterialBlock>();
  47. private _previewManager: PreviewManager;
  48. private _copiedNodes: GraphNode[] = [];
  49. private _copiedFrame: Nullable<GraphFrame> = null;
  50. private _mouseLocationX = 0;
  51. private _mouseLocationY = 0;
  52. private _onWidgetKeyUpPointer: any;
  53. private _previewHost: Nullable<HTMLElement>;
  54. private _popUpWindow: Window;
  55. /**
  56. * Creates a node and recursivly creates its parent nodes from it's input
  57. * @param nodeMaterialBlock
  58. */
  59. public createNodeFromObject(block: NodeMaterialBlock, recursion = true) {
  60. if (this._blocks.indexOf(block) !== -1) {
  61. return this._graphCanvas.nodes.filter(n => n.block === block)[0];
  62. }
  63. this._blocks.push(block);
  64. if (this.props.globalState.nodeMaterial!.attachedBlocks.indexOf(block) === -1) {
  65. this.props.globalState.nodeMaterial!.attachedBlocks.push(block);
  66. }
  67. if (block.isFinalMerger) {
  68. this.props.globalState.nodeMaterial!.addOutputNode(block);
  69. }
  70. // Connections
  71. if (block.inputs.length) {
  72. for (var input of block.inputs) {
  73. if (input.isConnected && recursion) {
  74. this.createNodeFromObject(input.sourceBlock!);
  75. }
  76. }
  77. }
  78. // Graph
  79. const node = this._graphCanvas.appendBlock(block);
  80. // Links
  81. if (block.inputs.length && recursion) {
  82. for (var input of block.inputs) {
  83. if (input.isConnected) {
  84. this._graphCanvas.connectPorts(input.connectedPoint!, input);
  85. }
  86. }
  87. }
  88. return node;
  89. }
  90. addValueNode(type: string) {
  91. let nodeType: NodeMaterialBlockConnectionPointTypes = BlockTools.GetConnectionNodeTypeFromString(type);
  92. let newInputBlock = new InputBlock(type, undefined, nodeType);
  93. return this.createNodeFromObject(newInputBlock);
  94. }
  95. componentDidMount() {
  96. if (this.props.globalState.hostDocument) {
  97. this._graphCanvas = (this.refs["graphCanvas"] as GraphCanvasComponent);
  98. this._previewManager = new PreviewManager(this.props.globalState.hostDocument.getElementById("preview-canvas") as HTMLCanvasElement, this.props.globalState);
  99. }
  100. if (navigator.userAgent.indexOf("Mobile") !== -1) {
  101. ((this.props.globalState.hostDocument || document).querySelector(".blocker") as HTMLElement).style.visibility = "visible";
  102. }
  103. this.build();
  104. }
  105. componentWillUnmount() {
  106. if (this.props.globalState.hostDocument) {
  107. this.props.globalState.hostDocument!.removeEventListener("keyup", this._onWidgetKeyUpPointer, false);
  108. }
  109. if (this._previewManager) {
  110. this._previewManager.dispose();
  111. }
  112. }
  113. constructor(props: IGraphEditorProps) {
  114. super(props);
  115. this.state = {
  116. showPreviewPopUp: false
  117. };
  118. this.props.globalState.onRebuildRequiredObservable.add(() => {
  119. if (this.props.globalState.nodeMaterial) {
  120. this.buildMaterial();
  121. }
  122. });
  123. this.props.globalState.onResetRequiredObservable.add(() => {
  124. this.build();
  125. if (this.props.globalState.nodeMaterial) {
  126. this.buildMaterial();
  127. }
  128. });
  129. this.props.globalState.onImportFrameObservable.add((source: any) => {
  130. const frameData = source.editorData.frames[0];
  131. // create new graph nodes for only blocks from frame (last blocks added)
  132. this.props.globalState.nodeMaterial.attachedBlocks.slice(-(frameData.blocks.length)).forEach((block: NodeMaterialBlock) => {
  133. this.createNodeFromObject(block);
  134. });
  135. this._graphCanvas.addFrame(frameData);
  136. this.reOrganize(this.props.globalState.nodeMaterial.editorData, true);
  137. })
  138. this.props.globalState.onZoomToFitRequiredObservable.add(() => {
  139. this.zoomToFit();
  140. });
  141. this.props.globalState.onReOrganizedRequiredObservable.add(() => {
  142. this.reOrganize();
  143. });
  144. this.props.globalState.onGetNodeFromBlock = (block) => {
  145. return this._graphCanvas.findNodeFromBlock(block);
  146. }
  147. this.props.globalState.hostDocument!.addEventListener("keydown", evt => {
  148. if ((evt.keyCode === 46 || evt.keyCode === 8) && !this.props.globalState.blockKeyboardEvents) { // Delete
  149. let selectedItems = this._graphCanvas.selectedNodes;
  150. for (var selectedItem of selectedItems) {
  151. selectedItem.dispose();
  152. let targetBlock = selectedItem.block;
  153. this.props.globalState.nodeMaterial!.removeBlock(targetBlock);
  154. let blockIndex = this._blocks.indexOf(targetBlock);
  155. if (blockIndex > -1) {
  156. this._blocks.splice(blockIndex, 1);
  157. }
  158. }
  159. if (this._graphCanvas.selectedLink) {
  160. this._graphCanvas.selectedLink.dispose();
  161. }
  162. if (this._graphCanvas.selectedFrame) {
  163. var frame = this._graphCanvas.selectedFrame;
  164. if(frame.isCollapsed) {
  165. while(frame.nodes.length > 0) {
  166. let targetBlock = frame.nodes[0].block;
  167. this.props.globalState.nodeMaterial!.removeBlock(targetBlock);
  168. let blockIndex = this._blocks.indexOf(targetBlock);
  169. if (blockIndex > -1) {
  170. this._blocks.splice(blockIndex, 1);
  171. }
  172. frame.nodes[0].dispose();
  173. }
  174. frame.isCollapsed = false;
  175. }
  176. else {
  177. frame.nodes.forEach(node => {
  178. node.enclosingFrameId = -1;
  179. });
  180. }
  181. this._graphCanvas.selectedFrame.dispose();
  182. }
  183. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  184. this.props.globalState.onRebuildRequiredObservable.notifyObservers();
  185. return;
  186. }
  187. if (!evt.ctrlKey || this.props.globalState.blockKeyboardEvents) {
  188. return;
  189. }
  190. if (evt.key === "c") { // Copy
  191. this._copiedNodes = [];
  192. this._copiedFrame = null;
  193. if (this._graphCanvas.selectedFrame) {
  194. this._copiedFrame = this._graphCanvas.selectedFrame;
  195. return;
  196. }
  197. let selectedItems = this._graphCanvas.selectedNodes;
  198. if (!selectedItems.length) {
  199. return;
  200. }
  201. let selectedItem = selectedItems[0] as GraphNode;
  202. if (!selectedItem.block) {
  203. return;
  204. }
  205. this._copiedNodes = selectedItems.slice(0);
  206. } else if (evt.key === "v") { // Paste
  207. const rootElement = this.props.globalState.hostDocument!.querySelector(".diagram-container") as HTMLDivElement;
  208. const zoomLevel = this._graphCanvas.zoom;
  209. let currentY = (this._mouseLocationY - rootElement.offsetTop - this._graphCanvas.y - 20) / zoomLevel;
  210. if (this._copiedFrame) {
  211. // New frame
  212. let newFrame = new GraphFrame(null, this._graphCanvas, true);
  213. this._graphCanvas.frames.push(newFrame);
  214. newFrame.width = this._copiedFrame.width;
  215. newFrame.height = this._copiedFrame.height;newFrame.width / 2
  216. newFrame.name = this._copiedFrame.name;
  217. newFrame.color = this._copiedFrame.color;
  218. let currentX = (this._mouseLocationX - rootElement.offsetLeft - this._graphCanvas.x) / zoomLevel;
  219. newFrame.x = currentX - newFrame.width / 2;
  220. newFrame.y = currentY;
  221. // Paste nodes
  222. if (this._copiedFrame.nodes.length) {
  223. currentX = newFrame.x + this._copiedFrame.nodes[0].x - this._copiedFrame.x;
  224. currentY = newFrame.y + this._copiedFrame.nodes[0].y - this._copiedFrame.y;
  225. this._graphCanvas._frameIsMoving = true;
  226. let newNodes = this.pasteSelection(this._copiedFrame.nodes, currentX, currentY);
  227. if (newNodes) {
  228. for (var node of newNodes) {
  229. newFrame.syncNode(node);
  230. }
  231. }
  232. this._graphCanvas._frameIsMoving = false;
  233. }
  234. if (this._copiedFrame.isCollapsed) {
  235. newFrame.isCollapsed = true;
  236. }
  237. // Select
  238. this.props.globalState.onSelectionChangedObservable.notifyObservers(newFrame);
  239. return;
  240. }
  241. if (!this._copiedNodes.length) {
  242. return;
  243. }
  244. let currentX = (this._mouseLocationX - rootElement.offsetLeft - this._graphCanvas.x - this.NodeWidth) / zoomLevel;
  245. this.pasteSelection(this._copiedNodes, currentX, currentY, true);
  246. }
  247. }, false);
  248. }
  249. reconnectNewNodes(nodeIndex: number, newNodes:GraphNode[], sourceNodes:GraphNode[], done: boolean[]) {
  250. if (done[nodeIndex]) {
  251. return;
  252. }
  253. const currentNode = newNodes[nodeIndex];
  254. const block = currentNode.block;
  255. const sourceNode = sourceNodes[nodeIndex];
  256. for (var inputIndex = 0; inputIndex < sourceNode.block.inputs.length; inputIndex++) {
  257. let sourceInput = sourceNode.block.inputs[inputIndex];
  258. const currentInput = block.inputs[inputIndex];
  259. if (!sourceInput.isConnected) {
  260. continue;
  261. }
  262. const sourceBlock = sourceInput.connectedPoint!.ownerBlock;
  263. const activeNodes = sourceNodes.filter(s => s.block === sourceBlock);
  264. if (activeNodes.length > 0) {
  265. const activeNode = activeNodes[0];
  266. let indexInList = sourceNodes.indexOf(activeNode);
  267. // First make sure to connect the other one
  268. this.reconnectNewNodes(indexInList, newNodes, sourceNodes, done);
  269. // Then reconnect
  270. const outputIndex = sourceBlock.outputs.indexOf(sourceInput.connectedPoint!);
  271. const newOutput = newNodes[indexInList].block.outputs[outputIndex];
  272. newOutput.connectTo(currentInput);
  273. } else {
  274. // Connect with outside blocks
  275. sourceInput._connectedPoint!.connectTo(currentInput);
  276. }
  277. this._graphCanvas.connectPorts(currentInput.connectedPoint!, currentInput);
  278. }
  279. currentNode.refresh();
  280. done[nodeIndex] = true;
  281. }
  282. pasteSelection(copiedNodes: GraphNode[], currentX: number, currentY: number, selectNew = false) {
  283. let originalNode: Nullable<GraphNode> = null;
  284. let newNodes:GraphNode[] = [];
  285. // Copy to prevent recursive side effects while creating nodes.
  286. copiedNodes = copiedNodes.slice();
  287. // Cancel selection
  288. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  289. // Create new nodes
  290. for (var node of copiedNodes) {
  291. let block = node.block;
  292. if (!block) {
  293. continue;
  294. }
  295. let clone = block.clone(this.props.globalState.nodeMaterial.getScene());
  296. if (!clone) {
  297. return;
  298. }
  299. let newNode = this.createNodeFromObject(clone, false);
  300. let x = 0;
  301. let y = 0;
  302. if (originalNode) {
  303. x = currentX + node.x - originalNode.x;
  304. y = currentY + node.y - originalNode.y;
  305. } else {
  306. originalNode = node;
  307. x = currentX;
  308. y = currentY;
  309. }
  310. newNode.x = x;
  311. newNode.y = y;
  312. newNode.cleanAccumulation();
  313. newNodes.push(newNode);
  314. if (selectNew) {
  315. this.props.globalState.onSelectionChangedObservable.notifyObservers(newNode);
  316. }
  317. }
  318. // Relink
  319. let done = new Array<boolean>(newNodes.length);
  320. for (var index = 0; index < newNodes.length; index++) {
  321. this.reconnectNewNodes(index, newNodes, copiedNodes, done);
  322. }
  323. return newNodes;
  324. }
  325. zoomToFit() {
  326. this._graphCanvas.zoomToFit();
  327. }
  328. buildMaterial() {
  329. if (!this.props.globalState.nodeMaterial) {
  330. return;
  331. }
  332. try {
  333. this.props.globalState.nodeMaterial.options.emitComments = true;
  334. this.props.globalState.nodeMaterial.build(true);
  335. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry("Node material build successful", false));
  336. }
  337. catch (err) {
  338. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry(err, true));
  339. }
  340. SerializationTools.UpdateLocations(this.props.globalState.nodeMaterial, this.props.globalState);
  341. this.props.globalState.onBuiltObservable.notifyObservers();
  342. }
  343. build() {
  344. let editorData = this.props.globalState.nodeMaterial.editorData;
  345. this._graphCanvas._isLoading = true; // Will help loading large graphes
  346. if (editorData instanceof Array) {
  347. editorData = {
  348. locations: editorData
  349. }
  350. }
  351. // setup the diagram model
  352. this._blocks = [];
  353. this._graphCanvas.reset();
  354. // Load graph of nodes from the material
  355. if (this.props.globalState.nodeMaterial) {
  356. this.loadGraph()
  357. }
  358. this.reOrganize(editorData);
  359. }
  360. loadGraph() {
  361. var material = this.props.globalState.nodeMaterial;
  362. material._vertexOutputNodes.forEach((n: any) => {
  363. this.createNodeFromObject(n, true);
  364. });
  365. material._fragmentOutputNodes.forEach((n: any) => {
  366. this.createNodeFromObject(n, true);
  367. });
  368. material.attachedBlocks.forEach((n: any) => {
  369. this.createNodeFromObject(n, true);
  370. });
  371. // Links
  372. material.attachedBlocks.forEach((n: any) => {
  373. if (n.inputs.length) {
  374. for (var input of n.inputs) {
  375. if (input.isConnected) {
  376. this._graphCanvas.connectPorts(input.connectedPoint!, input);
  377. }
  378. }
  379. }
  380. });
  381. }
  382. showWaitScreen() {
  383. this.props.globalState.hostDocument.querySelector(".wait-screen")?.classList.remove("hidden");
  384. }
  385. hideWaitScreen() {
  386. this.props.globalState.hostDocument.querySelector(".wait-screen")?.classList.add("hidden");
  387. }
  388. reOrganize(editorData: Nullable<IEditorData> = null, isImportingAFrame = false) {
  389. this.showWaitScreen();
  390. this._graphCanvas._isLoading = true; // Will help loading large graphes
  391. setTimeout(() => {
  392. if (!editorData || !editorData.locations) {
  393. this._graphCanvas.distributeGraph();
  394. } else {
  395. // Locations
  396. for (var location of editorData.locations) {
  397. for (var node of this._graphCanvas.nodes) {
  398. if (node.block && node.block.uniqueId === location.blockId) {
  399. node.x = location.x;
  400. node.y = location.y;
  401. node.cleanAccumulation();
  402. break;
  403. }
  404. }
  405. }
  406. if (!isImportingAFrame){
  407. this._graphCanvas.processEditorData(editorData);
  408. }
  409. }
  410. this._graphCanvas._isLoading = false;
  411. for (var node of this._graphCanvas.nodes) {
  412. node._refreshLinks();
  413. }
  414. this.hideWaitScreen();
  415. });
  416. }
  417. onPointerDown(evt: React.PointerEvent<HTMLDivElement>) {
  418. this._startX = evt.clientX;
  419. this._moveInProgress = true;
  420. evt.currentTarget.setPointerCapture(evt.pointerId);
  421. }
  422. onPointerUp(evt: React.PointerEvent<HTMLDivElement>) {
  423. this._moveInProgress = false;
  424. evt.currentTarget.releasePointerCapture(evt.pointerId);
  425. }
  426. resizeColumns(evt: React.PointerEvent<HTMLDivElement>, forLeft = true) {
  427. if (!this._moveInProgress) {
  428. return;
  429. }
  430. const deltaX = evt.clientX - this._startX;
  431. const rootElement = evt.currentTarget.ownerDocument!.getElementById("node-editor-graph-root") as HTMLDivElement;
  432. if (forLeft) {
  433. this._leftWidth += deltaX;
  434. this._leftWidth = Math.max(150, Math.min(400, this._leftWidth));
  435. DataStorage.WriteNumber("LeftWidth", this._leftWidth);
  436. } else {
  437. this._rightWidth -= deltaX;
  438. this._rightWidth = Math.max(250, Math.min(500, this._rightWidth));
  439. DataStorage.WriteNumber("RightWidth", this._rightWidth);
  440. rootElement.ownerDocument!.getElementById("preview")!.style.height = this._rightWidth + "px";
  441. }
  442. rootElement.style.gridTemplateColumns = this.buildColumnLayout();
  443. this._startX = evt.clientX;
  444. }
  445. buildColumnLayout() {
  446. return `${this._leftWidth}px 4px calc(100% - ${this._leftWidth + 8 + this._rightWidth}px) 4px ${this._rightWidth}px`;
  447. }
  448. emitNewBlock(event: React.DragEvent<HTMLDivElement>) {
  449. var data = event.dataTransfer.getData("babylonjs-material-node") as string;
  450. let newNode: GraphNode;
  451. if(data.indexOf("Custom") > -1) {
  452. let storageData = localStorage.getItem(data);
  453. if(storageData) {
  454. let frameData = JSON.parse(storageData);
  455. //edit position before loading.
  456. let newX = (event.clientX - event.currentTarget.offsetLeft - this._graphCanvas.x - this.NodeWidth) / this._graphCanvas.zoom;
  457. let newY = (event.clientY - event.currentTarget.offsetTop - this._graphCanvas.y - 20) / this._graphCanvas.zoom;;
  458. let oldX = frameData.editorData.frames[0].x;
  459. let oldY = frameData.editorData.frames[0].y;
  460. frameData.editorData.frames[0].x = newX;
  461. frameData.editorData.frames[0].y = newY;
  462. for (var location of frameData.editorData.locations) {
  463. location.x += newX - oldX;
  464. location.y += newY - oldY;
  465. }
  466. SerializationTools.AddFrameToMaterial(frameData, this.props.globalState, this.props.globalState.nodeMaterial);
  467. this._graphCanvas.frames[this._graphCanvas.frames.length -1].cleanAccumulation();
  468. this.forceUpdate();
  469. return;
  470. }
  471. }
  472. if (data.indexOf("Block") === -1) {
  473. newNode = this.addValueNode(data);
  474. }
  475. else {
  476. let block = BlockTools.GetBlockFromString(data, this.props.globalState.nodeMaterial.getScene(), this.props.globalState.nodeMaterial)!;
  477. if (block.isUnique) {
  478. const className = block.getClassName();
  479. for (var other of this._blocks) {
  480. if (other !== block && other.getClassName() === className) {
  481. this.props.globalState.onErrorMessageDialogRequiredObservable.notifyObservers(`You can only have one ${className} per graph`);
  482. return;
  483. }
  484. }
  485. }
  486. block.autoConfigure(this.props.globalState.nodeMaterial);
  487. newNode = this.createNodeFromObject(block);
  488. };
  489. let x = event.clientX - event.currentTarget.offsetLeft - this._graphCanvas.x - this.NodeWidth;
  490. let y = event.clientY - event.currentTarget.offsetTop - this._graphCanvas.y - 20;
  491. newNode.x = x / this._graphCanvas.zoom;
  492. newNode.y = y / this._graphCanvas.zoom;
  493. newNode.cleanAccumulation();
  494. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  495. this.props.globalState.onSelectionChangedObservable.notifyObservers(newNode);
  496. let block = newNode.block;
  497. x -= this.NodeWidth + 150;
  498. block.inputs.forEach((connection) => {
  499. if (connection.connectedPoint) {
  500. var existingNodes = this._graphCanvas.nodes.filter((n) => { return n.block === (connection as any).connectedPoint.ownerBlock });
  501. let connectedNode = existingNodes[0];
  502. if (connectedNode.x === 0 && connectedNode.y === 0) {
  503. connectedNode.x = x / this._graphCanvas.zoom;
  504. connectedNode.y = y / this._graphCanvas.zoom;
  505. connectedNode.cleanAccumulation();
  506. y += 80;
  507. }
  508. }
  509. });
  510. this.forceUpdate();
  511. }
  512. handlePopUp = () => {
  513. this.setState({
  514. showPreviewPopUp : true
  515. });
  516. this.createPopUp();
  517. this.props.globalState.hostWindow.addEventListener('beforeunload', this.handleClosingPopUp);
  518. }
  519. handleClosingPopUp = () => {
  520. this._previewManager.dispose();
  521. this._popUpWindow.close();
  522. this.setState({
  523. showPreviewPopUp: false
  524. }, () => this.initiatePreviewArea()
  525. );
  526. }
  527. initiatePreviewArea = (canvas: HTMLCanvasElement = this.props.globalState.hostDocument.getElementById("preview-canvas") as HTMLCanvasElement) => {
  528. this._previewManager = new PreviewManager(canvas, this.props.globalState);
  529. }
  530. createPopUp = () => {
  531. const userOptions = {
  532. original: true,
  533. popup: true,
  534. overlay: false,
  535. embedMode: false,
  536. enableClose: true,
  537. handleResize: true,
  538. enablePopup: true,
  539. };
  540. const options = {
  541. embedHostWidth: "100%",
  542. ...userOptions
  543. };
  544. const popUpWindow = this.createPopupWindow("PREVIEW AREA", "_PreviewHostWindow");
  545. if (popUpWindow) {
  546. popUpWindow.addEventListener('beforeunload', this.handleClosingPopUp);
  547. const parentControl = popUpWindow.document.getElementById('node-editor-graph-root');
  548. this.createPreviewMeshControlHost(options, parentControl);
  549. this.createPreviewHost(options, parentControl);
  550. if (parentControl) {
  551. this.fixPopUpStyles(parentControl.ownerDocument!);
  552. this.initiatePreviewArea(parentControl.ownerDocument!.getElementById("preview-canvas") as HTMLCanvasElement);
  553. }
  554. }
  555. }
  556. createPopupWindow = (title: string, windowVariableName: string, width = 500, height = 500): Window | null => {
  557. const windowCreationOptionsList = {
  558. width: width,
  559. height: height,
  560. top: (this.props.globalState.hostWindow.innerHeight - width) / 2 + window.screenY,
  561. left: (this.props.globalState.hostWindow.innerWidth - height) / 2 + window.screenX
  562. };
  563. var windowCreationOptions = Object.keys(windowCreationOptionsList)
  564. .map(
  565. (key) => key + '=' + (windowCreationOptionsList as any)[key]
  566. )
  567. .join(',');
  568. const popupWindow = this.props.globalState.hostWindow.open("", title, windowCreationOptions);
  569. if (!popupWindow) {
  570. return null;
  571. }
  572. const parentDocument = popupWindow.document;
  573. parentDocument.title = title;
  574. parentDocument.body.style.width = "100%";
  575. parentDocument.body.style.height = "100%";
  576. parentDocument.body.style.margin = "0";
  577. parentDocument.body.style.padding = "0";
  578. let parentControl = parentDocument.createElement("div");
  579. parentControl.style.width = "100%";
  580. parentControl.style.height = "100%";
  581. parentControl.style.margin = "0";
  582. parentControl.style.padding = "0";
  583. parentControl.style.display = "grid";
  584. parentControl.style.gridTemplateRows = "40px auto";
  585. parentControl.id = 'node-editor-graph-root';
  586. parentControl.className = 'right-panel';
  587. popupWindow.document.body.appendChild(parentControl);
  588. this.copyStyles(this.props.globalState.hostWindow.document, parentDocument);
  589. (this as any)[windowVariableName] = popupWindow;
  590. this._popUpWindow = popupWindow;
  591. return popupWindow;
  592. }
  593. copyStyles = (sourceDoc: HTMLDocument, targetDoc: HTMLDocument) => {
  594. const styleContainer = [];
  595. for (var index = 0; index < sourceDoc.styleSheets.length; index++) {
  596. var styleSheet: any = sourceDoc.styleSheets[index];
  597. try {
  598. if (styleSheet.href) { // for <link> elements loading CSS from a URL
  599. const newLinkEl = sourceDoc.createElement('link');
  600. newLinkEl.rel = 'stylesheet';
  601. newLinkEl.href = styleSheet.href;
  602. targetDoc.head!.appendChild(newLinkEl);
  603. styleContainer.push(newLinkEl);
  604. }
  605. else if (styleSheet.cssRules) { // for <style> elements
  606. const newStyleEl = sourceDoc.createElement('style');
  607. for (var cssRule of styleSheet.cssRules) {
  608. newStyleEl.appendChild(sourceDoc.createTextNode(cssRule.cssText));
  609. }
  610. targetDoc.head!.appendChild(newStyleEl);
  611. styleContainer.push(newStyleEl);
  612. }
  613. } catch (e) {
  614. console.log(e);
  615. }
  616. }
  617. }
  618. createPreviewMeshControlHost = (options: IInternalPreviewAreaOptions, parentControl: Nullable<HTMLElement>) => {
  619. // Prepare the preview control host
  620. if (parentControl) {
  621. const host = parentControl.ownerDocument!.createElement("div");
  622. host.id = "PreviewMeshControl-host";
  623. host.style.width = options.embedHostWidth || "auto";
  624. parentControl.appendChild(host);
  625. const PreviewMeshControlComponentHost = React.createElement(PreviewMeshControlComponent, {
  626. globalState: this.props.globalState,
  627. togglePreviewAreaComponent: this.handlePopUp
  628. });
  629. ReactDOM.render(PreviewMeshControlComponentHost, host);
  630. }
  631. }
  632. createPreviewHost = (options: IInternalPreviewAreaOptions, parentControl: Nullable<HTMLElement>) => {
  633. // Prepare the preview host
  634. if (parentControl) {
  635. const host = parentControl.ownerDocument!.createElement("div");
  636. host.id = "PreviewAreaComponent-host";
  637. host.style.width = options.embedHostWidth || "auto";
  638. host.style.display = "grid";
  639. host.style.gridRow = '2';
  640. host.style.gridTemplateRows = "auto 40px";
  641. parentControl.appendChild(host);
  642. this._previewHost = host;
  643. if (!options.overlay) {
  644. this._previewHost.style.position = "relative";
  645. }
  646. }
  647. if (this._previewHost) {
  648. const PreviewAreaComponentHost = React.createElement(PreviewAreaComponent, {
  649. globalState: this.props.globalState,
  650. width: 200
  651. });
  652. ReactDOM.render(PreviewAreaComponentHost, this._previewHost);
  653. }
  654. }
  655. fixPopUpStyles = (document: Document) => {
  656. const previewContainer = document.getElementById("preview");
  657. if (previewContainer) {
  658. previewContainer.style.height = "auto";
  659. previewContainer.style.gridRow = "1";
  660. }
  661. const previewConfigBar = document.getElementById("preview-config-bar");
  662. if (previewConfigBar) {
  663. previewConfigBar.style.gridRow = "2";
  664. }
  665. const newWindowButton = document.getElementById('preview-new-window');
  666. if (newWindowButton) {
  667. newWindowButton.style.display = 'none';
  668. }
  669. const previewMeshBar = document.getElementById('preview-mesh-bar');
  670. if (previewMeshBar) {
  671. previewMeshBar.style.gridTemplateColumns = "auto 1fr 40px 40px";
  672. }
  673. }
  674. render() {
  675. return (
  676. <Portal globalState={this.props.globalState}>
  677. <div id="node-editor-graph-root" style={
  678. {
  679. gridTemplateColumns: this.buildColumnLayout()
  680. }}
  681. onMouseMove={evt => {
  682. this._mouseLocationX = evt.pageX;
  683. this._mouseLocationY = evt.pageY;
  684. }}
  685. onMouseDown={(evt) => {
  686. if ((evt.target as HTMLElement).nodeName === "INPUT") {
  687. return;
  688. }
  689. this.props.globalState.blockKeyboardEvents = false;
  690. }}
  691. >
  692. {/* Node creation menu */}
  693. <NodeListComponent globalState={this.props.globalState} />
  694. <div id="leftGrab"
  695. onPointerDown={evt => this.onPointerDown(evt)}
  696. onPointerUp={evt => this.onPointerUp(evt)}
  697. onPointerMove={evt => this.resizeColumns(evt)}
  698. ></div>
  699. {/* The node graph diagram */}
  700. <div className="diagram-container"
  701. onDrop={event => {
  702. this.emitNewBlock(event);
  703. }}
  704. onDragOver={event => {
  705. event.preventDefault();
  706. }}
  707. >
  708. <GraphCanvasComponent ref={"graphCanvas"}
  709. globalState={this.props.globalState}
  710. onEmitNewBlock={ block => {
  711. return this.createNodeFromObject(block);
  712. }
  713. }/>
  714. </div>
  715. <div id="rightGrab"
  716. onPointerDown={evt => this.onPointerDown(evt)}
  717. onPointerUp={evt => this.onPointerUp(evt)}
  718. onPointerMove={evt => this.resizeColumns(evt, false)}
  719. ></div>
  720. {/* Property tab */}
  721. <div className="right-panel">
  722. <PropertyTabComponent globalState={this.props.globalState} />
  723. {!this.state.showPreviewPopUp ? <PreviewMeshControlComponent globalState={this.props.globalState} togglePreviewAreaComponent={this.handlePopUp} /> : null }
  724. {!this.state.showPreviewPopUp ? <PreviewAreaComponent globalState={this.props.globalState} width={this._rightWidth} /> : null}
  725. </div>
  726. <LogComponent globalState={this.props.globalState} />
  727. </div>
  728. <MessageDialogComponent globalState={this.props.globalState} />
  729. <div className="blocker">
  730. Node Material Editor runs only on desktop
  731. </div>
  732. <div className="wait-screen hidden">
  733. Processing...please wait
  734. </div>
  735. </Portal>
  736. );
  737. }
  738. }