graphEditor.tsx 34 KB

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