graphEditor.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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 './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. require("./main.scss");
  23. interface IGraphEditorProps {
  24. globalState: GlobalState;
  25. }
  26. export class GraphEditor extends React.Component<IGraphEditorProps> {
  27. private readonly NodeWidth = 100;
  28. private _graphCanvas: GraphCanvasComponent;
  29. private _startX: number;
  30. private _moveInProgress: boolean;
  31. private _leftWidth = DataStorage.ReadNumber("LeftWidth", 200);
  32. private _rightWidth = DataStorage.ReadNumber("RightWidth", 300);
  33. private _blocks = new Array<NodeMaterialBlock>();
  34. private _previewManager: PreviewManager;
  35. private _copiedNodes: GraphNode[] = [];
  36. private _copiedFrame: Nullable<GraphFrame> = null;
  37. private _mouseLocationX = 0;
  38. private _mouseLocationY = 0;
  39. private _onWidgetKeyUpPointer: any;
  40. /**
  41. * Creates a node and recursivly creates its parent nodes from it's input
  42. * @param nodeMaterialBlock
  43. */
  44. public createNodeFromObject(block: NodeMaterialBlock) {
  45. if (this._blocks.indexOf(block) !== -1) {
  46. return this._graphCanvas.nodes.filter(n => n.block === block)[0];
  47. }
  48. this._blocks.push(block);
  49. if (this.props.globalState.nodeMaterial!.attachedBlocks.indexOf(block) === -1) {
  50. this.props.globalState.nodeMaterial!.attachedBlocks.push(block);
  51. }
  52. if (block.isFinalMerger) {
  53. this.props.globalState.nodeMaterial!.addOutputNode(block);
  54. }
  55. // Connections
  56. if (block.inputs.length) {
  57. for (var input of block.inputs) {
  58. if (input.isConnected) {
  59. this.createNodeFromObject(input.sourceBlock!);
  60. }
  61. }
  62. }
  63. // Graph
  64. const node = this._graphCanvas.appendBlock(block);
  65. // Links
  66. if (block.inputs.length) {
  67. for (var input of block.inputs) {
  68. if (input.isConnected) {
  69. this._graphCanvas.connectPorts(input.connectedPoint!, input);
  70. }
  71. }
  72. }
  73. return node;
  74. }
  75. addValueNode(type: string) {
  76. let nodeType: NodeMaterialBlockConnectionPointTypes = BlockTools.GetConnectionNodeTypeFromString(type);
  77. let newInputBlock = new InputBlock(type, undefined, nodeType);
  78. return this.createNodeFromObject(newInputBlock)
  79. }
  80. componentDidMount() {
  81. if (this.props.globalState.hostDocument) {
  82. this._graphCanvas = (this.refs["graphCanvas"] as GraphCanvasComponent);
  83. this._previewManager = new PreviewManager(this.props.globalState.hostDocument.getElementById("preview-canvas") as HTMLCanvasElement, this.props.globalState);
  84. }
  85. if (navigator.userAgent.indexOf("Mobile") !== -1) {
  86. ((this.props.globalState.hostDocument || document).querySelector(".blocker") as HTMLElement).style.visibility = "visible";
  87. }
  88. this.build();
  89. }
  90. componentWillUnmount() {
  91. if (this.props.globalState.hostDocument) {
  92. this.props.globalState.hostDocument!.removeEventListener("keyup", this._onWidgetKeyUpPointer, false);
  93. }
  94. if (this._previewManager) {
  95. this._previewManager.dispose();
  96. }
  97. }
  98. constructor(props: IGraphEditorProps) {
  99. super(props);
  100. this.props.globalState.onRebuildRequiredObservable.add(() => {
  101. if (this.props.globalState.nodeMaterial) {
  102. this.buildMaterial();
  103. }
  104. });
  105. this.props.globalState.onResetRequiredObservable.add(() => {
  106. this.build();
  107. if (this.props.globalState.nodeMaterial) {
  108. this.buildMaterial();
  109. }
  110. });
  111. this.props.globalState.onZoomToFitRequiredObservable.add(() => {
  112. this.zoomToFit();
  113. });
  114. this.props.globalState.onReOrganizedRequiredObservable.add(() => {
  115. this.reOrganize();
  116. });
  117. this.props.globalState.onGetNodeFromBlock = (block) => {
  118. return this._graphCanvas.findNodeFromBlock(block);
  119. }
  120. this.props.globalState.hostDocument!.addEventListener("keydown", evt => {
  121. if (evt.keyCode === 46 && !this.props.globalState.blockKeyboardEvents) { // Delete
  122. let selectedItems = this._graphCanvas.selectedNodes;
  123. for (var selectedItem of selectedItems) {
  124. selectedItem.dispose();
  125. let targetBlock = selectedItem.block;
  126. this.props.globalState.nodeMaterial!.removeBlock(targetBlock);
  127. let blockIndex = this._blocks.indexOf(targetBlock);
  128. if (blockIndex > -1) {
  129. this._blocks.splice(blockIndex, 1);
  130. }
  131. }
  132. if (this._graphCanvas.selectedLink) {
  133. this._graphCanvas.selectedLink.dispose();
  134. }
  135. if (this._graphCanvas.selectedFrame) {
  136. this._graphCanvas.selectedFrame.dispose();
  137. }
  138. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  139. this.props.globalState.onRebuildRequiredObservable.notifyObservers();
  140. return;
  141. }
  142. if (!evt.ctrlKey || this.props.globalState.blockKeyboardEvents) {
  143. return;
  144. }
  145. if (evt.key === "c") { // Copy
  146. this._copiedNodes = [];
  147. this._copiedFrame = null;
  148. if (this._graphCanvas.selectedFrame) {
  149. this._copiedFrame = this._graphCanvas.selectedFrame;
  150. return;
  151. }
  152. let selectedItems = this._graphCanvas.selectedNodes;
  153. if (!selectedItems.length) {
  154. return;
  155. }
  156. let selectedItem = selectedItems[0] as GraphNode;
  157. if (!selectedItem.block) {
  158. return;
  159. }
  160. this._copiedNodes = selectedItems.slice(0);
  161. } else if (evt.key === "v") { // Paste
  162. const rootElement = this.props.globalState.hostDocument!.querySelector(".diagram-container") as HTMLDivElement;
  163. const zoomLevel = this._graphCanvas.zoom;
  164. let currentY = (this._mouseLocationY - rootElement.offsetTop - this._graphCanvas.y - 20) / zoomLevel;
  165. if (this._copiedFrame) {
  166. // New frame
  167. let newFrame = new GraphFrame(null, this._graphCanvas, true);
  168. this._graphCanvas.frames.push(newFrame);
  169. newFrame.width = this._copiedFrame.width;
  170. newFrame.height = this._copiedFrame.height;newFrame.width / 2
  171. newFrame.name = this._copiedFrame.name;
  172. newFrame.color = this._copiedFrame.color;
  173. let currentX = (this._mouseLocationX - rootElement.offsetLeft - this._graphCanvas.x) / zoomLevel;
  174. newFrame.x = currentX - newFrame.width / 2;
  175. newFrame.y = currentY;
  176. // Paste nodes
  177. if (this._copiedFrame.nodes.length) {
  178. currentX = newFrame.x + this._copiedFrame.nodes[0].x - this._copiedFrame.x;
  179. currentY = newFrame.y + this._copiedFrame.nodes[0].y - this._copiedFrame.y;
  180. this.pasteSelection(this._copiedFrame.nodes, currentX, currentY);
  181. }
  182. if (this._copiedFrame.isCollapsed) {
  183. newFrame.isCollapsed = true;
  184. }
  185. return;
  186. }
  187. if (!this._copiedNodes.length) {
  188. return;
  189. }
  190. let currentX = (this._mouseLocationX - rootElement.offsetLeft - this._graphCanvas.x - this.NodeWidth) / zoomLevel;
  191. this.pasteSelection(this._copiedNodes, currentX, currentY);
  192. }
  193. }, false);
  194. }
  195. reconnectNewNodes(nodeIndex: number, newNodes:GraphNode[], sourceNodes:GraphNode[], done: boolean[]) {
  196. if (done[nodeIndex]) {
  197. return;
  198. }
  199. const currentNode = newNodes[nodeIndex];
  200. const block = currentNode.block;
  201. const sourceNode = sourceNodes[nodeIndex];
  202. for (var inputIndex = 0; inputIndex < sourceNode.block.inputs.length; inputIndex++) {
  203. let sourceInput = sourceNode.block.inputs[inputIndex];
  204. const currentInput = block.inputs[inputIndex];
  205. if (!sourceInput.isConnected) {
  206. continue;
  207. }
  208. const sourceBlock = sourceInput.connectedPoint!.ownerBlock;
  209. const activeNodes = sourceNodes.filter(s => s.block === sourceBlock);
  210. if (activeNodes.length > 0) {
  211. const activeNode = activeNodes[0];
  212. let indexInList = sourceNodes.indexOf(activeNode);
  213. // First make sure to connect the other one
  214. this.reconnectNewNodes(indexInList, newNodes, sourceNodes, done);
  215. // Then reconnect
  216. const outputIndex = sourceBlock.outputs.indexOf(sourceInput.connectedPoint!);
  217. const newOutput = newNodes[indexInList].block.outputs[outputIndex];
  218. newOutput.connectTo(currentInput);
  219. } else {
  220. // Connect with outside blocks
  221. sourceInput._connectedPoint!.connectTo(currentInput);
  222. }
  223. this._graphCanvas.connectPorts(currentInput.connectedPoint!, currentInput);
  224. }
  225. currentNode.refresh();
  226. done[nodeIndex] = true;
  227. }
  228. pasteSelection(copiedNodes: GraphNode[], currentX: number, currentY: number) {
  229. let originalNode: Nullable<GraphNode> = null;
  230. let newNodes:GraphNode[] = [];
  231. // Create new nodes
  232. for (var node of copiedNodes) {
  233. let block = node.block;
  234. if (!block) {
  235. continue;
  236. }
  237. let clone = block.clone(this.props.globalState.nodeMaterial.getScene());
  238. if (!clone) {
  239. return;
  240. }
  241. let newNode = this.createNodeFromObject(clone);
  242. let x = 0;
  243. let y = 0;
  244. if (originalNode) {
  245. x = currentX + node.x - originalNode.x;
  246. y = currentY + node.y - originalNode.y;
  247. } else {
  248. originalNode = node;
  249. x = currentX;
  250. y = currentY;
  251. }
  252. newNode.x = x;
  253. newNode.y = y;
  254. newNode.cleanAccumulation();
  255. newNodes.push(newNode);
  256. }
  257. // Relink
  258. let done = new Array<boolean>(newNodes.length);
  259. for (var index = 0; index < newNodes.length; index++) {
  260. this.reconnectNewNodes(index, newNodes, copiedNodes, done);
  261. }
  262. }
  263. zoomToFit() {
  264. this._graphCanvas.zoomToFit();
  265. }
  266. buildMaterial() {
  267. if (!this.props.globalState.nodeMaterial) {
  268. return;
  269. }
  270. try {
  271. this.props.globalState.nodeMaterial.build(true);
  272. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry("Node material build successful", false));
  273. }
  274. catch (err) {
  275. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry(err, true));
  276. }
  277. SerializationTools.UpdateLocations(this.props.globalState.nodeMaterial, this.props.globalState);
  278. }
  279. build() {
  280. let editorData = this.props.globalState.nodeMaterial.editorData;
  281. if (editorData instanceof Array) {
  282. editorData = {
  283. locations: editorData
  284. }
  285. }
  286. // setup the diagram model
  287. this._blocks = [];
  288. this._graphCanvas.reset();
  289. // Load graph of nodes from the material
  290. if (this.props.globalState.nodeMaterial) {
  291. var material = this.props.globalState.nodeMaterial;
  292. material._vertexOutputNodes.forEach((n: any) => {
  293. this.createNodeFromObject(n);
  294. });
  295. material._fragmentOutputNodes.forEach((n: any) => {
  296. this.createNodeFromObject(n);
  297. });
  298. material.attachedBlocks.forEach((n: any) => {
  299. this.createNodeFromObject(n);
  300. });
  301. // Links
  302. material.attachedBlocks.forEach((n: any) => {
  303. if (n.inputs.length) {
  304. for (var input of n.inputs) {
  305. if (input.isConnected) {
  306. this._graphCanvas.connectPorts(input.connectedPoint!, input);
  307. }
  308. }
  309. }
  310. });
  311. }
  312. this.reOrganize(editorData);
  313. }
  314. reOrganize(editorData: Nullable<IEditorData> = null) {
  315. if (!editorData || !editorData.locations) {
  316. this._graphCanvas.distributeGraph();
  317. } else {
  318. // Locations
  319. for (var location of editorData.locations) {
  320. for (var node of this._graphCanvas.nodes) {
  321. if (node.block && node.block.uniqueId === location.blockId) {
  322. node.x = location.x;
  323. node.y = location.y;
  324. node.cleanAccumulation();
  325. break;
  326. }
  327. }
  328. }
  329. this._graphCanvas.processEditorData(editorData);
  330. }
  331. }
  332. onPointerDown(evt: React.PointerEvent<HTMLDivElement>) {
  333. this._startX = evt.clientX;
  334. this._moveInProgress = true;
  335. evt.currentTarget.setPointerCapture(evt.pointerId);
  336. }
  337. onPointerUp(evt: React.PointerEvent<HTMLDivElement>) {
  338. this._moveInProgress = false;
  339. evt.currentTarget.releasePointerCapture(evt.pointerId);
  340. }
  341. resizeColumns(evt: React.PointerEvent<HTMLDivElement>, forLeft = true) {
  342. if (!this._moveInProgress) {
  343. return;
  344. }
  345. const deltaX = evt.clientX - this._startX;
  346. const rootElement = evt.currentTarget.ownerDocument!.getElementById("node-editor-graph-root") as HTMLDivElement;
  347. if (forLeft) {
  348. this._leftWidth += deltaX;
  349. this._leftWidth = Math.max(150, Math.min(400, this._leftWidth));
  350. DataStorage.StoreNumber("LeftWidth", this._leftWidth);
  351. } else {
  352. this._rightWidth -= deltaX;
  353. this._rightWidth = Math.max(250, Math.min(500, this._rightWidth));
  354. DataStorage.StoreNumber("RightWidth", this._rightWidth);
  355. rootElement.ownerDocument!.getElementById("preview")!.style.height = this._rightWidth + "px";
  356. }
  357. rootElement.style.gridTemplateColumns = this.buildColumnLayout();
  358. this._startX = evt.clientX;
  359. }
  360. buildColumnLayout() {
  361. return `${this._leftWidth}px 4px calc(100% - ${this._leftWidth + 8 + this._rightWidth}px) 4px ${this._rightWidth}px`;
  362. }
  363. emitNewBlock(event: React.DragEvent<HTMLDivElement>) {
  364. var data = event.dataTransfer.getData("babylonjs-material-node") as string;
  365. let newNode: GraphNode;
  366. if (data.indexOf("Block") === -1) {
  367. newNode = this.addValueNode(data);
  368. } else {
  369. let block = BlockTools.GetBlockFromString(data, this.props.globalState.nodeMaterial.getScene(), this.props.globalState.nodeMaterial)!;
  370. if (block.isUnique) {
  371. const className = block.getClassName();
  372. for (var other of this._blocks) {
  373. if (other !== block && other.getClassName() === className) {
  374. this.props.globalState.onErrorMessageDialogRequiredObservable.notifyObservers(`You can only have one ${className} per graph`);
  375. return;
  376. }
  377. }
  378. }
  379. block.autoConfigure(this.props.globalState.nodeMaterial);
  380. newNode = this.createNodeFromObject(block);
  381. };
  382. let x = event.clientX - event.currentTarget.offsetLeft - this._graphCanvas.x - this.NodeWidth;
  383. let y = event.clientY - event.currentTarget.offsetTop - this._graphCanvas.y - 20;
  384. newNode.x = x / this._graphCanvas.zoom;
  385. newNode.y = y / this._graphCanvas.zoom;
  386. newNode.cleanAccumulation();
  387. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  388. this.props.globalState.onSelectionChangedObservable.notifyObservers(newNode);
  389. let block = newNode.block;
  390. x -= this.NodeWidth + 150;
  391. block.inputs.forEach((connection) => {
  392. if (connection.connectedPoint) {
  393. var existingNodes = this._graphCanvas.nodes.filter((n) => { return n.block === (connection as any).connectedPoint.ownerBlock });
  394. let connectedNode = existingNodes[0];
  395. if (connectedNode.x === 0 && connectedNode.y === 0) {
  396. connectedNode.x = x / this._graphCanvas.zoom;
  397. connectedNode.y = y / this._graphCanvas.zoom;
  398. connectedNode.cleanAccumulation();
  399. y += 80;
  400. }
  401. }
  402. });
  403. this.forceUpdate();
  404. }
  405. render() {
  406. return (
  407. <Portal globalState={this.props.globalState}>
  408. <div id="node-editor-graph-root" style={
  409. {
  410. gridTemplateColumns: this.buildColumnLayout()
  411. }}
  412. onMouseMove={evt => {
  413. this._mouseLocationX = evt.pageX;
  414. this._mouseLocationY = evt.pageY;
  415. }}
  416. onMouseDown={(evt) => {
  417. if ((evt.target as HTMLElement).nodeName === "INPUT") {
  418. return;
  419. }
  420. this.props.globalState.blockKeyboardEvents = false;
  421. }}
  422. >
  423. {/* Node creation menu */}
  424. <NodeListComponent globalState={this.props.globalState} />
  425. <div id="leftGrab"
  426. onPointerDown={evt => this.onPointerDown(evt)}
  427. onPointerUp={evt => this.onPointerUp(evt)}
  428. onPointerMove={evt => this.resizeColumns(evt)}
  429. ></div>
  430. {/* The node graph diagram */}
  431. <div className="diagram-container"
  432. onDrop={event => {
  433. this.emitNewBlock(event);
  434. }}
  435. onDragOver={event => {
  436. event.preventDefault();
  437. }}
  438. >
  439. <GraphCanvasComponent ref={"graphCanvas"} globalState={this.props.globalState}/>
  440. </div>
  441. <div id="rightGrab"
  442. onPointerDown={evt => this.onPointerDown(evt)}
  443. onPointerUp={evt => this.onPointerUp(evt)}
  444. onPointerMove={evt => this.resizeColumns(evt, false)}
  445. ></div>
  446. {/* Property tab */}
  447. <div className="right-panel">
  448. <PropertyTabComponent globalState={this.props.globalState} />
  449. <PreviewMeshControlComponent globalState={this.props.globalState} />
  450. <PreviewAreaComponent globalState={this.props.globalState} width={this._rightWidth}/>
  451. </div>
  452. <LogComponent globalState={this.props.globalState} />
  453. </div>
  454. <MessageDialogComponent globalState={this.props.globalState} />
  455. <div className="blocker">
  456. Node Material Editor runs only on desktop
  457. </div>
  458. </Portal>
  459. );
  460. }
  461. }