graphEditor.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. import {
  2. DiagramEngine,
  3. DiagramModel,
  4. DiagramWidget,
  5. LinkModel
  6. } from "storm-react-diagrams";
  7. import * as React from "react";
  8. import * as dagre from "dagre";
  9. import { GlobalState } from './globalState';
  10. import { GenericNodeFactory } from './components/diagram/generic/genericNodeFactory';
  11. import { GenericNodeModel } from './components/diagram/generic/genericNodeModel';
  12. import { NodeMaterialBlock } from 'babylonjs/Materials/Node/nodeMaterialBlock';
  13. import { NodeMaterialConnectionPoint } from 'babylonjs/Materials/Node/nodeMaterialBlockConnectionPoint';
  14. import { NodeListComponent } from './components/nodeList/nodeListComponent';
  15. import { PropertyTabComponent } from './components/propertyTab/propertyTabComponent';
  16. import { Portal } from './portal';
  17. import { TextureNodeFactory } from './components/diagram/texture/textureNodeFactory';
  18. import { DefaultNodeModel } from './components/diagram/defaultNodeModel';
  19. import { TextureNodeModel } from './components/diagram/texture/textureNodeModel';
  20. import { DefaultPortModel } from './components/diagram/port/defaultPortModel';
  21. import { InputNodeFactory } from './components/diagram/input/inputNodeFactory';
  22. import { InputNodeModel } from './components/diagram/input/inputNodeModel';
  23. import { TextureBlock } from 'babylonjs/Materials/Node/Blocks/Dual/textureBlock';
  24. import { LogComponent, LogEntry } from './components/log/logComponent';
  25. import { LightBlock } from 'babylonjs/Materials/Node/Blocks/Dual/lightBlock';
  26. import { LightNodeModel } from './components/diagram/light/lightNodeModel';
  27. import { LightNodeFactory } from './components/diagram/light/lightNodeFactory';
  28. import { DataStorage } from './dataStorage';
  29. import { NodeMaterialBlockConnectionPointTypes } from 'babylonjs/Materials/Node/nodeMaterialBlockConnectionPointTypes';
  30. import { InputBlock } from 'babylonjs/Materials/Node/Blocks/Input/inputBlock';
  31. import { Nullable } from 'babylonjs/types';
  32. import { MessageDialogComponent } from './sharedComponents/messageDialog';
  33. import { BlockTools } from './blockTools';
  34. import { AdvancedLinkFactory } from './components/diagram/link/advancedLinkFactory';
  35. require("storm-react-diagrams/dist/style.min.css");
  36. require("./main.scss");
  37. require("./components/diagram/diagram.scss");
  38. /*
  39. Graph Editor Overview
  40. Storm React setup:
  41. GenericNodeModel - Represents the nodes in the graph and can be any node type (eg. texture, vector2, etc)
  42. GenericNodeWidget - Renders the node model in the graph
  43. GenericPortModel - Represents the input/output of a node (contained within each GenericNodeModel)
  44. Generating/modifying the graph:
  45. Generating node graph - the createNodeFromObject method is used to recursively create the graph
  46. Modifications to the graph - The listener in the constructor of GraphEditor listens for port changes and updates the node material based on changes
  47. Saving the graph/generating code - Not yet done
  48. */
  49. interface IGraphEditorProps {
  50. globalState: GlobalState;
  51. }
  52. export class NodeCreationOptions {
  53. nodeMaterialBlock: NodeMaterialBlock;
  54. type?: string;
  55. connection?: NodeMaterialConnectionPoint;
  56. }
  57. export class GraphEditor extends React.Component<IGraphEditorProps> {
  58. private readonly NodeWidth = 100;
  59. private _engine: DiagramEngine;
  60. private _model: DiagramModel;
  61. private _startX: number;
  62. private _moveInProgress: boolean;
  63. private _leftWidth = DataStorage.ReadNumber("LeftWidth", 200);
  64. private _rightWidth = DataStorage.ReadNumber("RightWidth", 300);
  65. private _nodes = new Array<DefaultNodeModel>();
  66. /** @hidden */
  67. public _toAdd: LinkModel[] | null = [];
  68. /**
  69. * Creates a node and recursivly creates its parent nodes from it's input
  70. * @param nodeMaterialBlock
  71. */
  72. public createNodeFromObject(options: NodeCreationOptions) {
  73. // Create new node in the graph
  74. var newNode: DefaultNodeModel;
  75. var filterInputs = [];
  76. if (options.nodeMaterialBlock instanceof TextureBlock) {
  77. newNode = new TextureNodeModel();
  78. filterInputs.push("uv");
  79. } else if (options.nodeMaterialBlock instanceof LightBlock) {
  80. newNode = new LightNodeModel();
  81. filterInputs.push("worldPosition");
  82. filterInputs.push("worldNormal");
  83. filterInputs.push("cameraPosition");
  84. } else if (options.nodeMaterialBlock instanceof InputBlock) {
  85. newNode = new InputNodeModel();
  86. } else {
  87. newNode = new GenericNodeModel();
  88. }
  89. if (options.nodeMaterialBlock.isFinalMerger) {
  90. this.props.globalState.nodeMaterial!.addOutputNode(options.nodeMaterialBlock);
  91. }
  92. this._nodes.push(newNode)
  93. this._model.addAll(newNode);
  94. if (options.nodeMaterialBlock) {
  95. newNode.prepare(options, this._nodes, this._model, this, filterInputs);
  96. }
  97. return newNode;
  98. }
  99. componentDidMount() {
  100. if (this.props.globalState.hostDocument) {
  101. var widget = (this.refs["test"] as DiagramWidget);
  102. widget.setState({ document: this.props.globalState.hostDocument })
  103. this.props.globalState.hostDocument!.addEventListener("keyup", widget.onKeyUpPointer as any, false);
  104. }
  105. }
  106. componentWillUnmount() {
  107. if (this.props.globalState.hostDocument) {
  108. var widget = (this.refs["test"] as DiagramWidget);
  109. this.props.globalState.hostDocument!.removeEventListener("keyup", widget.onKeyUpPointer as any, false);
  110. }
  111. }
  112. constructor(props: IGraphEditorProps) {
  113. super(props);
  114. // setup the diagram engine
  115. this._engine = new DiagramEngine();
  116. this._engine.installDefaultFactories()
  117. this._engine.registerNodeFactory(new GenericNodeFactory(this.props.globalState));
  118. this._engine.registerNodeFactory(new TextureNodeFactory(this.props.globalState));
  119. this._engine.registerNodeFactory(new LightNodeFactory(this.props.globalState));
  120. this._engine.registerNodeFactory(new InputNodeFactory(this.props.globalState));
  121. this._engine.registerLinkFactory(new AdvancedLinkFactory());
  122. this.props.globalState.onRebuildRequiredObservable.add(() => {
  123. if (this.props.globalState.nodeMaterial) {
  124. this.buildMaterial();
  125. }
  126. this.forceUpdate();
  127. });
  128. this.props.globalState.onResetRequiredObservable.add(() => {
  129. this.build();
  130. if (this.props.globalState.nodeMaterial) {
  131. this.buildMaterial();
  132. }
  133. });
  134. this.props.globalState.onUpdateRequiredObservable.add(() => {
  135. this.forceUpdate();
  136. });
  137. this.props.globalState.onZoomToFitRequiredObservable.add(() => {
  138. this.zoomToFit();
  139. });
  140. this.props.globalState.onReOrganizedRequiredObservable.add(() => {
  141. this.reOrganize();
  142. })
  143. this.build(true);
  144. }
  145. zoomToFit(retry = 0) {
  146. const xFactor = this._engine.canvas.clientWidth / this._engine.canvas.scrollWidth;
  147. const yFactor = this._engine.canvas.clientHeight / this._engine.canvas.scrollHeight;
  148. const zoomFactor = xFactor < yFactor ? xFactor : yFactor;
  149. if (zoomFactor === 1) {
  150. return;
  151. }
  152. this._engine.diagramModel.setZoomLevel(this._engine.diagramModel.getZoomLevel() * zoomFactor);
  153. this._engine.diagramModel.setOffset(0, 0);
  154. this._engine.repaintCanvas();
  155. retry++;
  156. if (retry < 4) {
  157. setTimeout(() => this.zoomToFit(retry), 1);
  158. }
  159. }
  160. distributeGraph() {
  161. let nodes = this.mapElements();
  162. let edges = this.mapEdges();
  163. let graph = new dagre.graphlib.Graph();
  164. graph.setGraph({});
  165. graph.setDefaultEdgeLabel(() => ({}));
  166. graph.graph().rankdir = "LR";
  167. //add elements to dagre graph
  168. nodes.forEach(node => {
  169. graph.setNode(node.id, node.metadata);
  170. });
  171. edges.forEach(edge => {
  172. if (edge.from && edge.to) {
  173. graph.setEdge(edge.from.id, edge.to.id);
  174. }
  175. });
  176. //auto-distribute
  177. dagre.layout(graph);
  178. return graph.nodes().map(node => graph.node(node));
  179. }
  180. mapElements() {
  181. let output = [];
  182. // dagre compatible format
  183. for (var nodeName in this._model.nodes) {
  184. let node = this._model.nodes[nodeName];
  185. let size = {
  186. width: node.width | 200,
  187. height: node.height | 100
  188. };
  189. output.push({ id: node.id, metadata: { ...size, id: node.id } });
  190. }
  191. return output;
  192. }
  193. mapEdges() {
  194. // returns links which connects nodes
  195. // we check are there both from and to nodes in the model. Sometimes links can be detached
  196. let output = [];
  197. for (var linkName in this._model.links) {
  198. let link = this._model.links[linkName];
  199. output.push({
  200. from: link.sourcePort!.parent,
  201. to: link.targetPort!.parent
  202. });
  203. }
  204. return output;
  205. }
  206. buildMaterial() {
  207. if (!this.props.globalState.nodeMaterial) {
  208. return;
  209. }
  210. try {
  211. this.props.globalState.nodeMaterial.build(true);
  212. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry("Node material build successful", false));
  213. }
  214. catch (err) {
  215. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry(err, true));
  216. }
  217. }
  218. build(needToWait = false) {
  219. // setup the diagram model
  220. this._model = new DiagramModel();
  221. // Listen to events
  222. this._model.addListener({
  223. nodesUpdated: (e) => {
  224. if (!e.isCreated) {
  225. // Block is deleted
  226. let targetBlock = (e.node as GenericNodeModel).block;
  227. if (targetBlock && targetBlock.isFinalMerger) {
  228. this.props.globalState.nodeMaterial!.removeOutputNode(targetBlock);
  229. }
  230. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  231. }
  232. },
  233. linksUpdated: (e) => {
  234. if (!e.isCreated) {
  235. // Link is deleted
  236. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  237. let sourcePort = e.link.sourcePort as DefaultPortModel;
  238. var link = DefaultPortModel.SortInputOutput(sourcePort, e.link.targetPort as DefaultPortModel);
  239. if (link) {
  240. if (link.input.connection && link.output.connection) {
  241. if (link.input.connection.connectedPoint) {
  242. // Disconnect standard nodes
  243. link.output.connection.disconnectFrom(link.input.connection);
  244. link.input.syncWithNodeMaterialConnectionPoint(link.input.connection);
  245. link.output.syncWithNodeMaterialConnectionPoint(link.output.connection);
  246. }
  247. }
  248. } else {
  249. if (!e.link.targetPort && e.link.sourcePort && (e.link.sourcePort as DefaultPortModel).position === "input") {
  250. // Drag from input port, we are going to build an input for it
  251. let input = e.link.sourcePort as DefaultPortModel;
  252. let nodeModel = this.addValueNode(BlockTools.GetStringFromConnectionNodeType(input.connection!.type));
  253. let link = nodeModel.ports.output.link(input);
  254. nodeModel.x = e.link.points[1].x - this.NodeWidth;
  255. nodeModel.y = e.link.points[1].y;
  256. setTimeout(() => {
  257. this._model.addLink(link);
  258. input.syncWithNodeMaterialConnectionPoint(input.connection!);
  259. nodeModel.ports.output.syncWithNodeMaterialConnectionPoint(nodeModel.ports.output.connection!);
  260. this.forceUpdate();
  261. }, 1);
  262. nodeModel.ports.output.connection!.connectTo(input.connection!);
  263. this.props.globalState.onRebuildRequiredObservable.notifyObservers();
  264. }
  265. }
  266. this.forceUpdate();
  267. return;
  268. }
  269. e.link.addListener({
  270. sourcePortChanged: () => {
  271. },
  272. targetPortChanged: () => {
  273. // Link is created with a target port
  274. var link = DefaultPortModel.SortInputOutput(e.link.sourcePort as DefaultPortModel, e.link.targetPort as DefaultPortModel);
  275. if (link) {
  276. if (link.output.connection && link.input.connection) {
  277. // Disconnect previous connection
  278. for (var key in link.input.links) {
  279. let other = link.input.links[key];
  280. if ((other.getSourcePort() as DefaultPortModel).connection !== (link.output as DefaultPortModel).connection &&
  281. (other.getTargetPort() as DefaultPortModel).connection !== (link.output as DefaultPortModel).connection
  282. ) {
  283. other.remove();
  284. }
  285. }
  286. try {
  287. link.output.connection.connectTo(link.input.connection);
  288. }
  289. catch (err) {
  290. link.output.remove();
  291. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry(err, true));
  292. this.props.globalState.onErrorMessageDialogRequiredObservable.notifyObservers(err);
  293. }
  294. this.forceUpdate();
  295. }
  296. if (this.props.globalState.nodeMaterial) {
  297. this.buildMaterial();
  298. }
  299. }
  300. }
  301. })
  302. }
  303. });
  304. // Load graph of nodes from the material
  305. if (this.props.globalState.nodeMaterial) {
  306. var material: any = this.props.globalState.nodeMaterial;
  307. material._vertexOutputNodes.forEach((n: any) => {
  308. this.createNodeFromObject({ nodeMaterialBlock: n });
  309. })
  310. material._fragmentOutputNodes.forEach((n: any) => {
  311. this.createNodeFromObject({ nodeMaterialBlock: n });
  312. })
  313. }
  314. // load model into engine
  315. setTimeout(() => {
  316. if (this._toAdd) {
  317. this._model.addAll(...this._toAdd);
  318. }
  319. this._toAdd = null;
  320. this._engine.setDiagramModel(this._model);
  321. this.forceUpdate();
  322. this.reOrganize();
  323. }, needToWait ? 500 : 1);
  324. }
  325. reOrganize() {
  326. let nodes = this.distributeGraph();
  327. nodes.forEach(node => {
  328. for (var nodeName in this._model.nodes) {
  329. let modelNode = this._model.nodes[nodeName];
  330. if (modelNode.id === node.id) {
  331. modelNode.setPosition(node.x - node.width / 2, node.y - node.height / 2);
  332. return;
  333. }
  334. }
  335. });
  336. this.forceUpdate();
  337. }
  338. addValueNode(type: string) {
  339. let nodeType: NodeMaterialBlockConnectionPointTypes = BlockTools.GetConnectionNodeTypeFromString(type);
  340. let newInputBlock = new InputBlock(type, undefined, nodeType);
  341. newInputBlock.setDefaultValue();
  342. var localNode = this.createNodeFromObject({ type: type, nodeMaterialBlock: newInputBlock })
  343. return localNode;
  344. }
  345. onPointerDown(evt: React.PointerEvent<HTMLDivElement>) {
  346. this._startX = evt.clientX;
  347. this._moveInProgress = true;
  348. evt.currentTarget.setPointerCapture(evt.pointerId);
  349. }
  350. onPointerUp(evt: React.PointerEvent<HTMLDivElement>) {
  351. this._moveInProgress = false;
  352. evt.currentTarget.releasePointerCapture(evt.pointerId);
  353. }
  354. resizeColumns(evt: React.PointerEvent<HTMLDivElement>, forLeft = true) {
  355. if (!this._moveInProgress) {
  356. return;
  357. }
  358. const deltaX = evt.clientX - this._startX;
  359. const rootElement = evt.currentTarget.ownerDocument!.getElementById("node-editor-graph-root") as HTMLDivElement;
  360. if (forLeft) {
  361. this._leftWidth += deltaX;
  362. this._leftWidth = Math.max(150, Math.min(400, this._leftWidth));
  363. DataStorage.StoreNumber("LeftWidth", this._leftWidth);
  364. } else {
  365. this._rightWidth -= deltaX;
  366. this._rightWidth = Math.max(250, Math.min(500, this._rightWidth));
  367. DataStorage.StoreNumber("RightWidth", this._rightWidth);
  368. }
  369. rootElement.style.gridTemplateColumns = this.buildColumnLayout();
  370. this._startX = evt.clientX;
  371. }
  372. buildColumnLayout() {
  373. return `${this._leftWidth}px 4px calc(100% - ${this._leftWidth + 8 + this._rightWidth}px) 4px ${this._rightWidth}px`;
  374. }
  375. emitNewBlock(event: React.DragEvent<HTMLDivElement>) {
  376. var data = event.dataTransfer.getData("babylonjs-material-node") as string;
  377. let nodeModel: Nullable<DefaultNodeModel> = null;
  378. if (data.indexOf("Block") === -1) {
  379. nodeModel = this.addValueNode(data);
  380. } else {
  381. let block = BlockTools.GetBlockFromString(data);
  382. if (block) {
  383. nodeModel = this.createNodeFromObject({ nodeMaterialBlock: block });
  384. }
  385. };
  386. if (nodeModel) {
  387. const zoomLevel = this._engine.diagramModel.getZoomLevel() / 100.0;
  388. let x = (event.clientX - event.currentTarget.offsetLeft - this._engine.diagramModel.getOffsetX() - this.NodeWidth) / zoomLevel;
  389. let y = (event.clientY - event.currentTarget.offsetTop - this._engine.diagramModel.getOffsetY() - 20) / zoomLevel;
  390. nodeModel.setPosition(x, y);
  391. }
  392. this.forceUpdate();
  393. }
  394. render() {
  395. return (
  396. <Portal globalState={this.props.globalState}>
  397. <div id="node-editor-graph-root" style={
  398. {
  399. gridTemplateColumns: this.buildColumnLayout()
  400. }
  401. }>
  402. {/* Node creation menu */}
  403. <NodeListComponent globalState={this.props.globalState} />
  404. <div id="leftGrab"
  405. onPointerDown={evt => this.onPointerDown(evt)}
  406. onPointerUp={evt => this.onPointerUp(evt)}
  407. onPointerMove={evt => this.resizeColumns(evt)}
  408. ></div>
  409. {/* The node graph diagram */}
  410. <div className="diagram-container"
  411. onDrop={event => {
  412. this.emitNewBlock(event);
  413. }}
  414. onDragOver={event => {
  415. event.preventDefault();
  416. }}
  417. >
  418. <DiagramWidget className="diagram" deleteKeys={[46]} ref={"test"}
  419. allowLooseLinks={false}
  420. inverseZoom={true} diagramEngine={this._engine} maxNumberPointsPerLink={0} />
  421. </div>
  422. <div id="rightGrab"
  423. onPointerDown={evt => this.onPointerDown(evt)}
  424. onPointerUp={evt => this.onPointerUp(evt)}
  425. onPointerMove={evt => this.resizeColumns(evt, false)}
  426. ></div>
  427. {/* Property tab */}
  428. <PropertyTabComponent globalState={this.props.globalState} />
  429. <LogComponent globalState={this.props.globalState} />
  430. </div>
  431. <MessageDialogComponent globalState={this.props.globalState} />
  432. </Portal>
  433. );
  434. }
  435. }