graphEditor.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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._engine.zoomToFit();
  139. });
  140. this.props.globalState.onReOrganizedRequiredObservable.add(() => {
  141. this.reOrganize();
  142. })
  143. this.build(true);
  144. }
  145. distributeGraph() {
  146. let nodes = this.mapElements();
  147. let edges = this.mapEdges();
  148. let graph = new dagre.graphlib.Graph();
  149. graph.setGraph({});
  150. graph.setDefaultEdgeLabel(() => ({}));
  151. graph.graph().rankdir = "LR";
  152. //add elements to dagre graph
  153. nodes.forEach(node => {
  154. graph.setNode(node.id, node.metadata);
  155. });
  156. edges.forEach(edge => {
  157. if (edge.from && edge.to) {
  158. graph.setEdge(edge.from.id, edge.to.id);
  159. }
  160. });
  161. //auto-distribute
  162. dagre.layout(graph);
  163. return graph.nodes().map(node => graph.node(node));
  164. }
  165. mapElements() {
  166. let output = [];
  167. // dagre compatible format
  168. for (var nodeName in this._model.nodes) {
  169. let node = this._model.nodes[nodeName];
  170. let size = {
  171. width: node.width | 200,
  172. height: node.height | 100
  173. };
  174. output.push({ id: node.id, metadata: { ...size, id: node.id } });
  175. }
  176. return output;
  177. }
  178. mapEdges() {
  179. // returns links which connects nodes
  180. // we check are there both from and to nodes in the model. Sometimes links can be detached
  181. let output = [];
  182. for (var linkName in this._model.links) {
  183. let link = this._model.links[linkName];
  184. output.push({
  185. from: link.sourcePort!.parent,
  186. to: link.targetPort!.parent
  187. });
  188. }
  189. return output;
  190. }
  191. buildMaterial() {
  192. if (!this.props.globalState.nodeMaterial) {
  193. return;
  194. }
  195. try {
  196. this.props.globalState.nodeMaterial.build(true);
  197. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry("Node material build successful", false));
  198. }
  199. catch (err) {
  200. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry(err, true));
  201. }
  202. }
  203. build(needToWait = false) {
  204. // setup the diagram model
  205. this._model = new DiagramModel();
  206. // Listen to events
  207. this._model.addListener({
  208. nodesUpdated: (e) => {
  209. if (!e.isCreated) {
  210. // Block is deleted
  211. let targetBlock = (e.node as GenericNodeModel).block;
  212. if (targetBlock && targetBlock.isFinalMerger) {
  213. this.props.globalState.nodeMaterial!.removeOutputNode(targetBlock);
  214. }
  215. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  216. }
  217. },
  218. linksUpdated: (e) => {
  219. if (!e.isCreated) {
  220. // Link is deleted
  221. this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
  222. let sourcePort = e.link.sourcePort as DefaultPortModel;
  223. var link = DefaultPortModel.SortInputOutput(sourcePort, e.link.targetPort as DefaultPortModel);
  224. if (link) {
  225. if (link.input.connection && link.output.connection) {
  226. if (link.input.connection.connectedPoint) {
  227. // Disconnect standard nodes
  228. link.output.connection.disconnectFrom(link.input.connection);
  229. link.input.syncWithNodeMaterialConnectionPoint(link.input.connection);
  230. link.output.syncWithNodeMaterialConnectionPoint(link.output.connection);
  231. }
  232. }
  233. } else {
  234. if (!e.link.targetPort && e.link.sourcePort && (e.link.sourcePort as DefaultPortModel).position === "input") {
  235. // Drag from input port, we are going to build an input for it
  236. let input = e.link.sourcePort as DefaultPortModel;
  237. let nodeModel = this.addValueNode(BlockTools.GetStringFromConnectionNodeType(input.connection!.type));
  238. let link = nodeModel.ports.output.link(input);
  239. nodeModel.x = e.link.points[1].x - this.NodeWidth;
  240. nodeModel.y = e.link.points[1].y;
  241. setTimeout(() => {
  242. this._model.addLink(link);
  243. input.syncWithNodeMaterialConnectionPoint(input.connection!);
  244. nodeModel.ports.output.syncWithNodeMaterialConnectionPoint(nodeModel.ports.output.connection!);
  245. this.forceUpdate();
  246. }, 1);
  247. nodeModel.ports.output.connection!.connectTo(input.connection!);
  248. this.props.globalState.onRebuildRequiredObservable.notifyObservers();
  249. }
  250. }
  251. this.forceUpdate();
  252. return;
  253. }
  254. e.link.addListener({
  255. sourcePortChanged: () => {
  256. },
  257. targetPortChanged: () => {
  258. // Link is created with a target port
  259. var link = DefaultPortModel.SortInputOutput(e.link.sourcePort as DefaultPortModel, e.link.targetPort as DefaultPortModel);
  260. if (link) {
  261. if (link.output.connection && link.input.connection) {
  262. // Disconnect previous connection
  263. for (var key in link.input.links) {
  264. let other = link.input.links[key];
  265. if ((other.getSourcePort() as DefaultPortModel).connection !== (link.output as DefaultPortModel).connection &&
  266. (other.getTargetPort() as DefaultPortModel).connection !== (link.output as DefaultPortModel).connection
  267. ) {
  268. other.remove();
  269. }
  270. }
  271. try {
  272. link.output.connection.connectTo(link.input.connection);
  273. }
  274. catch (err) {
  275. link.output.remove();
  276. this.props.globalState.onLogRequiredObservable.notifyObservers(new LogEntry(err, true));
  277. this.props.globalState.onErrorMessageDialogRequiredObservable.notifyObservers(err);
  278. }
  279. this.forceUpdate();
  280. }
  281. if (this.props.globalState.nodeMaterial) {
  282. this.buildMaterial();
  283. }
  284. }
  285. }
  286. })
  287. }
  288. });
  289. // Load graph of nodes from the material
  290. if (this.props.globalState.nodeMaterial) {
  291. var material: any = this.props.globalState.nodeMaterial;
  292. material._vertexOutputNodes.forEach((n: any) => {
  293. this.createNodeFromObject({ nodeMaterialBlock: n });
  294. })
  295. material._fragmentOutputNodes.forEach((n: any) => {
  296. this.createNodeFromObject({ nodeMaterialBlock: n });
  297. })
  298. }
  299. // load model into engine
  300. setTimeout(() => {
  301. if (this._toAdd) {
  302. this._model.addAll(...this._toAdd);
  303. }
  304. this._toAdd = null;
  305. this._engine.setDiagramModel(this._model);
  306. this.forceUpdate();
  307. this.reOrganize();
  308. }, needToWait ? 500 : 1);
  309. }
  310. reOrganize() {
  311. let nodes = this.distributeGraph();
  312. nodes.forEach(node => {
  313. for (var nodeName in this._model.nodes) {
  314. let modelNode = this._model.nodes[nodeName];
  315. if (modelNode.id === node.id) {
  316. modelNode.setPosition(node.x - node.width / 2, node.y - node.height / 2);
  317. return;
  318. }
  319. }
  320. });
  321. this.forceUpdate();
  322. }
  323. addValueNode(type: string) {
  324. let nodeType: NodeMaterialBlockConnectionPointTypes = BlockTools.GetConnectionNodeTypeFromString(type);
  325. let newInputBlock = new InputBlock(type, undefined, nodeType);
  326. newInputBlock.setDefaultValue();
  327. var localNode = this.createNodeFromObject({ type: type, nodeMaterialBlock: newInputBlock })
  328. return localNode;
  329. }
  330. onPointerDown(evt: React.PointerEvent<HTMLDivElement>) {
  331. this._startX = evt.clientX;
  332. this._moveInProgress = true;
  333. evt.currentTarget.setPointerCapture(evt.pointerId);
  334. }
  335. onPointerUp(evt: React.PointerEvent<HTMLDivElement>) {
  336. this._moveInProgress = false;
  337. evt.currentTarget.releasePointerCapture(evt.pointerId);
  338. }
  339. resizeColumns(evt: React.PointerEvent<HTMLDivElement>, forLeft = true) {
  340. if (!this._moveInProgress) {
  341. return;
  342. }
  343. const deltaX = evt.clientX - this._startX;
  344. const rootElement = evt.currentTarget.ownerDocument!.getElementById("node-editor-graph-root") as HTMLDivElement;
  345. if (forLeft) {
  346. this._leftWidth += deltaX;
  347. this._leftWidth = Math.max(150, Math.min(400, this._leftWidth));
  348. DataStorage.StoreNumber("LeftWidth", this._leftWidth);
  349. } else {
  350. this._rightWidth -= deltaX;
  351. this._rightWidth = Math.max(250, Math.min(500, this._rightWidth));
  352. DataStorage.StoreNumber("RightWidth", this._rightWidth);
  353. }
  354. rootElement.style.gridTemplateColumns = this.buildColumnLayout();
  355. this._startX = evt.clientX;
  356. }
  357. buildColumnLayout() {
  358. return `${this._leftWidth}px 4px calc(100% - ${this._leftWidth + 8 + this._rightWidth}px) 4px ${this._rightWidth}px`;
  359. }
  360. emitNewBlock(event: React.DragEvent<HTMLDivElement>) {
  361. var data = event.dataTransfer.getData("babylonjs-material-node") as string;
  362. let nodeModel: Nullable<DefaultNodeModel> = null;
  363. if (data.indexOf("Block") === -1) {
  364. nodeModel = this.addValueNode(data);
  365. } else {
  366. let block = BlockTools.GetBlockFromString(data);
  367. if (block) {
  368. nodeModel = this.createNodeFromObject({ nodeMaterialBlock: block });
  369. }
  370. };
  371. if (nodeModel) {
  372. const zoomLevel = this._engine.diagramModel.getZoomLevel() / 100.0;
  373. let x = (event.clientX - event.currentTarget.offsetLeft - this._engine.diagramModel.getOffsetX() - this.NodeWidth) / zoomLevel;
  374. let y = (event.clientY - event.currentTarget.offsetTop - this._engine.diagramModel.getOffsetY() - 20) / zoomLevel;
  375. nodeModel.setPosition(x, y);
  376. }
  377. this.forceUpdate();
  378. }
  379. render() {
  380. return (
  381. <Portal globalState={this.props.globalState}>
  382. <div id="node-editor-graph-root" style={
  383. {
  384. gridTemplateColumns: this.buildColumnLayout()
  385. }
  386. }>
  387. {/* Node creation menu */}
  388. <NodeListComponent globalState={this.props.globalState} />
  389. <div id="leftGrab"
  390. onPointerDown={evt => this.onPointerDown(evt)}
  391. onPointerUp={evt => this.onPointerUp(evt)}
  392. onPointerMove={evt => this.resizeColumns(evt)}
  393. ></div>
  394. {/* The node graph diagram */}
  395. <div className="diagram-container"
  396. onDrop={event => {
  397. this.emitNewBlock(event);
  398. }}
  399. onDragOver={event => {
  400. event.preventDefault();
  401. }}
  402. >
  403. <DiagramWidget className="diagram" deleteKeys={[46]} ref={"test"}
  404. allowLooseLinks={false}
  405. inverseZoom={true} diagramEngine={this._engine} maxNumberPointsPerLink={0} />
  406. </div>
  407. <div id="rightGrab"
  408. onPointerDown={evt => this.onPointerDown(evt)}
  409. onPointerUp={evt => this.onPointerUp(evt)}
  410. onPointerMove={evt => this.resizeColumns(evt, false)}
  411. ></div>
  412. {/* Property tab */}
  413. <PropertyTabComponent globalState={this.props.globalState} />
  414. <LogComponent globalState={this.props.globalState} />
  415. </div>
  416. <MessageDialogComponent globalState={this.props.globalState} />
  417. </Portal>
  418. );
  419. }
  420. }