graphEditor.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. import {
  2. DiagramEngine,
  3. DiagramModel,
  4. DiagramWidget,
  5. MoveCanvasAction
  6. } from "storm-react-diagrams";
  7. import * as React from "react";
  8. import { GlobalState } from '../globalState';
  9. import { GenericNodeFactory } from './customDiragramNodes/generic/genericNodeFactory';
  10. import { NodeMaterialBlockConnectionPointTypes } from 'babylonjs/Materials/Node/nodeMaterialBlockConnectionPointTypes';
  11. import { GenericNodeModel } from './customDiragramNodes/generic/genericNodeModel';
  12. import { GenericPortModel } from './customDiragramNodes/generic/genericPortModel';
  13. import { Engine } from 'babylonjs/Engines/engine';
  14. import { LineContainerComponent } from "../sharedComponents/lineContainerComponent"
  15. import { ButtonLineComponent } from '../sharedComponents/buttonLineComponent';
  16. import { NodeMaterialBlock } from 'babylonjs/Materials/Node/nodeMaterialBlock';
  17. import { NodeMaterialConnectionPoint } from 'babylonjs/Materials/Node/nodeMaterialBlockConnectionPoint';
  18. import { Texture } from 'babylonjs/Materials/Textures/texture';
  19. import { Vector2, Vector3, Vector4, Matrix } from 'babylonjs/Maths/math';
  20. import { AlphaTestBlock } from 'babylonjs/Materials/Node/Blocks/Fragment/alphaTestBlock';
  21. import { FragmentOutputBlock } from 'babylonjs/Materials/Node/Blocks/Fragment/fragmentOutputBlock';
  22. import { ImageProcessingBlock } from 'babylonjs/Materials/Node/Blocks/Fragment/imageProcessingBlock';
  23. import { RGBAMergerBlock } from 'babylonjs/Materials/Node/Blocks/Fragment/rgbaMergerBlock';
  24. import { RGBASplitterBlock } from 'babylonjs/Materials/Node/Blocks/Fragment/rgbaSplitterBlock';
  25. import { TextureBlock } from 'babylonjs/Materials/Node/Blocks/Fragment/textureBlock';
  26. import { BonesBlock } from 'babylonjs/Materials/Node/Blocks/Vertex/bonesBlock';
  27. import { InstancesBlock } from 'babylonjs/Materials/Node/Blocks/Vertex/instancesBlock';
  28. import { MorphTargetsBlock } from 'babylonjs/Materials/Node/Blocks/Vertex/morphTargetsBlock';
  29. import { VertexOutputBlock } from 'babylonjs/Materials/Node/Blocks/Vertex/vertexOutputBlock';
  30. import { FogBlock } from 'babylonjs/Materials/Node/Blocks/Dual/fogBlock';
  31. import { AddBlock } from 'babylonjs/Materials/Node/Blocks/addBlock';
  32. import { ClampBlock } from 'babylonjs/Materials/Node/Blocks/clampBlock';
  33. import { MatrixMultiplicationBlock } from 'babylonjs/Materials/Node/Blocks/matrixMultiplicationBlock';
  34. import { MultiplyBlock } from 'babylonjs/Materials/Node/Blocks/multiplyBlock';
  35. import { Vector2TransformBlock } from 'babylonjs/Materials/Node/Blocks/vector2TransformBlock';
  36. import { Vector3TransformBlock } from 'babylonjs/Materials/Node/Blocks/vector3TransformBlock';
  37. import { Vector4TransformBlock } from 'babylonjs/Materials/Node/Blocks/vector4TransformBlock';
  38. require("storm-react-diagrams/dist/style.min.css");
  39. require("./main.scss");
  40. /*
  41. Graph Editor Overview
  42. Storm React setup:
  43. GenericNodeModel - Represents the nodes in the graph and can be any node type (eg. texture, vector2, etc)
  44. GenericNodeWidget - Renders the node model in the graph
  45. GenericPortModel - Represents the input/output of a node (contained within each GenericNodeModel)
  46. Generating/modifying the graph:
  47. Generating node graph - the createNodeFromObject method is used to recursively create the graph
  48. Modifications to the graph - The listener in the constructor of GraphEditor listens for port changes and updates the node material based on changes
  49. Saving the graph/generating code - Not yet done
  50. */
  51. interface IGraphEditorProps {
  52. globalState: GlobalState;
  53. }
  54. export class GraphEditor extends React.Component<IGraphEditorProps> {
  55. private _engine:DiagramEngine;
  56. private _model: DiagramModel;
  57. private _nodes = new Array<GenericNodeModel>();
  58. /**
  59. * Current row/column position used when adding new nodes
  60. */
  61. private _rowPos = new Array<number>()
  62. /**
  63. * Creates a node and recursivly creates its parent nodes from it's input
  64. * @param nodeMaterialBlock
  65. */
  66. public createNodeFromObject(
  67. options:{
  68. column:number,
  69. nodeMaterialBlock?:NodeMaterialBlock
  70. }
  71. ){
  72. // Update rows/columns
  73. if(this._rowPos[options.column] == undefined){
  74. this._rowPos[options.column] = 0;
  75. }else{
  76. this._rowPos[options.column]++;
  77. }
  78. // Create new node in the graph
  79. var outputNode = new GenericNodeModel();
  80. this._nodes.push(outputNode)
  81. outputNode.setPosition(1600-(300*options.column), 200*this._rowPos[options.column])
  82. this._model.addAll(outputNode);
  83. if(options.nodeMaterialBlock){
  84. outputNode.block = options.nodeMaterialBlock
  85. outputNode.headerLabels.push({text: options.nodeMaterialBlock.getClassName()})
  86. // Create output ports
  87. options.nodeMaterialBlock._outputs.forEach((connection:any)=>{
  88. var outputPort = new GenericPortModel(connection.name, "output");
  89. outputPort.syncWithNodeMaterialConnectionPoint(connection);
  90. outputNode.addPort(outputPort)
  91. })
  92. // Create input ports and nodes if they exist
  93. options.nodeMaterialBlock._inputs.forEach((connection)=>{
  94. var inputPort = new GenericPortModel(connection.name, "input");
  95. inputPort.connection = connection;
  96. outputNode.addPort(inputPort)
  97. if(connection._connectedPoint){
  98. // Block is not a leaf node, create node for the given block type
  99. var connectedNode;
  100. var existingNodes = this._nodes.filter((n)=>{return n.block == (connection as any)._connectedPoint._ownerBlock});
  101. if(existingNodes.length == 0){
  102. connectedNode = this.createNodeFromObject({column: options.column+1, nodeMaterialBlock: connection._connectedPoint._ownerBlock});
  103. }else{
  104. connectedNode = existingNodes[0];
  105. }
  106. let link = connectedNode.ports[connection._connectedPoint.name].link(inputPort);
  107. this._model.addAll(link);
  108. }else {
  109. // Create value node for the connection
  110. var type = ""
  111. if(connection.type == NodeMaterialBlockConnectionPointTypes.Texture){
  112. type = "Texture"
  113. } else if(connection.type == NodeMaterialBlockConnectionPointTypes.Matrix){
  114. type = "Matrix"
  115. } else if(connection.type & NodeMaterialBlockConnectionPointTypes.Vector3OrColor3){
  116. type = "Vector3"
  117. } else if(connection.type & NodeMaterialBlockConnectionPointTypes.Vector2){
  118. type = "Vector2"
  119. }else if(connection.type & NodeMaterialBlockConnectionPointTypes.Vector3OrColor3OrVector4OrColor4){
  120. type = "Vector4"
  121. }
  122. // Create links
  123. var localNode = this.addValueNode(type, options.column+1, connection);
  124. var ports = localNode.getPorts()
  125. for(var key in ports){
  126. let link = (ports[key] as GenericPortModel).link(inputPort);
  127. this._model.addAll(link);
  128. }
  129. }
  130. })
  131. }
  132. return outputNode;
  133. }
  134. componentDidMount(){
  135. if(this.props.globalState.hostDocument){
  136. var widget = (this.refs["test"] as DiagramWidget);
  137. widget.setState({document: this.props.globalState.hostDocument})
  138. this.props.globalState.hostDocument!.addEventListener("keyup", widget.onKeyUpPointer as any, false);
  139. }
  140. }
  141. componentWillUnmount(){
  142. if(this.props.globalState.hostDocument){
  143. var widget = (this.refs["test"] as DiagramWidget);
  144. this.props.globalState.hostDocument!.removeEventListener("keyup", widget.onKeyUpPointer as any, false);
  145. }
  146. }
  147. constructor(props: IGraphEditorProps) {
  148. super(props);
  149. // setup the diagram engine
  150. this._engine = new DiagramEngine();
  151. this._engine.installDefaultFactories()
  152. this._engine.registerNodeFactory(new GenericNodeFactory());
  153. // setup the diagram model
  154. this._model = new DiagramModel();
  155. // Listen to events to connect/disconnect blocks or
  156. this._model.addListener({
  157. linksUpdated: (e)=>{
  158. if(!e.isCreated){
  159. // Link is deleted
  160. console.log("link deleted");
  161. var link = GenericPortModel.SortInputOutput(e.link.sourcePort as GenericPortModel, e.link.targetPort as GenericPortModel);
  162. console.log(link)
  163. if(link){
  164. if(link.output.connection && link.input.connection){
  165. // Disconnect standard nodes
  166. console.log("disconnected "+link.output.connection.name+" from "+link.input.connection.name)
  167. link.output.connection.disconnectFrom(link.input.connection)
  168. link.input.syncWithNodeMaterialConnectionPoint(link.input.connection)
  169. link.output.syncWithNodeMaterialConnectionPoint(link.output.connection)
  170. }else if(link.input.connection && link.input.connection.value){
  171. console.log("value link removed");
  172. link.input.connection.value = null;
  173. }else{
  174. console.log("invalid link error");
  175. }
  176. }
  177. }else{
  178. console.log("link created")
  179. console.log(e.link.sourcePort)
  180. }
  181. e.link.addListener({
  182. sourcePortChanged: ()=>{
  183. console.log("port change")
  184. },
  185. targetPortChanged: ()=>{
  186. // Link is created with a target port
  187. console.log("Link set to target")
  188. var link = GenericPortModel.SortInputOutput(e.link.sourcePort as GenericPortModel, e.link.targetPort as GenericPortModel);
  189. if(link){
  190. if(link.output.connection && link.input.connection){
  191. console.log("link standard blocks")
  192. link.output.connection.connectTo(link.input.connection)
  193. }else if(link.input.connection){
  194. console.log("link value to standard block")
  195. link.input.connection.value = link.output.getValue();
  196. }
  197. if(this.props.globalState.nodeMaterial){
  198. this.props.globalState.nodeMaterial.build()
  199. }
  200. }
  201. }
  202. })
  203. },
  204. nodesUpdated: (e)=>{
  205. if(e.isCreated){
  206. console.log("new node")
  207. }else{
  208. console.log("node deleted")
  209. }
  210. }
  211. })
  212. // Load graph of nodes from the material
  213. if(this.props.globalState.nodeMaterial){
  214. var material:any = this.props.globalState.nodeMaterial;
  215. material._vertexOutputNodes.forEach((n:any)=>{
  216. this.createNodeFromObject({column: 0, nodeMaterialBlock: n});
  217. })
  218. material._fragmentOutputNodes.forEach((n:any)=>{
  219. this.createNodeFromObject({column: 0, nodeMaterialBlock: n});
  220. })
  221. }
  222. // Zoom out a bit at the start
  223. this._model.setZoomLevel(20)
  224. // load model into engine
  225. this._engine.setDiagramModel(this._model);
  226. }
  227. addNodeFromClass(ObjectClass:typeof NodeMaterialBlock){
  228. var block = new ObjectClass(ObjectClass.prototype.getClassName()+"sdfsdf")
  229. var localNode = this.createNodeFromObject({column: 0, nodeMaterialBlock: block})
  230. var widget = (this.refs["test"] as DiagramWidget);
  231. this.forceUpdate()
  232. // This is needed to fix link offsets when created, (eg. create a fog block)
  233. // Todo figure out how to correct this without this
  234. setTimeout(() => {
  235. widget.startFiringAction(new MoveCanvasAction(1,0, this._model));
  236. }, 500);
  237. return localNode
  238. }
  239. addValueNode(type: string, column = 0, connection?: NodeMaterialConnectionPoint){
  240. var localNode = this.createNodeFromObject({column: column})
  241. var outPort = new GenericPortModel(type, "output");
  242. if(type == "Texture"){
  243. outPort.getValue = ()=>{
  244. return localNode.texture;
  245. }
  246. if(connection && connection.value){
  247. localNode.texture = connection.value
  248. }else{
  249. localNode.texture = new Texture(null, Engine.LastCreatedScene)
  250. }
  251. }else if(type == "Vector2"){
  252. outPort.getValue = ()=>{
  253. return localNode.vector2;
  254. }
  255. if(connection && connection.value){
  256. localNode.vector2 = connection.value
  257. }else{
  258. localNode.vector2 = new Vector2()
  259. }
  260. }else if(type == "Vector3"){
  261. outPort.getValue = ()=>{
  262. return localNode.vector3;
  263. }
  264. if(connection && connection.value){
  265. localNode.vector3 = connection.value
  266. }else{
  267. localNode.vector3 = new Vector3()
  268. }
  269. }else if(type == "Vector4"){
  270. outPort.getValue = ()=>{
  271. return localNode.vector4;
  272. }
  273. if(connection && connection.value){
  274. localNode.vector4 = connection.value
  275. }else{
  276. localNode.vector4 = new Vector4(0,0,0,1)
  277. }
  278. }else if(type == "Matrix"){
  279. outPort.getValue = ()=>{
  280. return localNode.matrix;
  281. }
  282. if(connection && connection.value){
  283. localNode.matrix = connection.value
  284. }else{
  285. localNode.matrix = new Matrix()
  286. }
  287. }else{
  288. console.log("Node type "+type+"is not supported")
  289. }
  290. localNode.addPort(outPort)
  291. this.forceUpdate()
  292. return localNode;
  293. }
  294. // Block types used to create the menu from
  295. allBlocks = {
  296. Fragment: [AlphaTestBlock, FragmentOutputBlock, ImageProcessingBlock, RGBAMergerBlock, RGBASplitterBlock, TextureBlock],
  297. Vertex: [BonesBlock, InstancesBlock, MorphTargetsBlock, VertexOutputBlock],
  298. Dual: [FogBlock],
  299. Other: [AddBlock, ClampBlock, MatrixMultiplicationBlock, MultiplyBlock, Vector2TransformBlock, Vector3TransformBlock, Vector4TransformBlock],
  300. Value: ["Texture", "Vector2", "Vector3", "Matrix"],
  301. }
  302. render() {
  303. // Create node menu
  304. var blockMenu = []
  305. for(var key in this.allBlocks){
  306. var blockList = (this.allBlocks as any)[key].map((b:any)=>{
  307. var label = typeof b === "string" ? b : b.prototype.getClassName()
  308. var onClick =typeof b === "string" ? () => {this.addValueNode(b)} : () => {this.addNodeFromClass(b)};
  309. return <ButtonLineComponent label={label} onClick={onClick} />
  310. })
  311. blockMenu.push(
  312. <LineContainerComponent title={key+" blocks"}>
  313. {blockList}
  314. </LineContainerComponent>
  315. )
  316. }
  317. return (
  318. <div id="node-editor-graph-root" style={{
  319. display: "flex",
  320. height: "100%",
  321. background: "#464646",
  322. }}>
  323. {/* Node creation menu */}
  324. <div id="actionTabs" style={{width: "170px", borderRightStyle: "solid", borderColor: "grey", borderWidth: "1px" }} >
  325. <div className="tabs" style={{gridTemplateRows: "0px 1fr"}}>
  326. <div className="labels"/>
  327. <div className="panes">
  328. <div className="pane">
  329. {blockMenu}
  330. </div>
  331. </div>
  332. </div>
  333. </div>
  334. {/* The node graph diagram */}
  335. <DiagramWidget deleteKeys={[46]} ref={"test"} inverseZoom={true} className="srd-demo-canvas" diagramEngine={this._engine} maxNumberPointsPerLink={0} />
  336. </div>
  337. );
  338. }
  339. }