java - 如何将 OpenGL 上下文放入我当前的线程中,未找到 opengl 上下文

标签 java opengl lwjgl event-listener

我正在开发一个世界编辑器,以获取乐趣并使用 Java 和 JLWGL。到目前为止一切正常。现在我尝试创建一个窗口,我可以在其中添加例如要使用的地形或新模型。问题是,当我尝试从主线程创建地形时,它会被创建并显示,但是当我尝试通过按钮事件监听器调用它时,我收到错误:在当前线程中找不到 OpenGL 上下文。 我基本上知道为什么会出现错误。我用来获取输入并单击按钮的框架没有 opengl 上下文。

我现在的问题是:如何将 opengl 上下文获取到当前帧? 欢迎任何帮助,如果您需要其他类(class),请告诉我。

这确实是错误,因为如果我运行generateTerrain(args);从我的主要内容来看,它工作得很好,只要我在事件监听器 addTerrain.addActionListener 中使用它,并且在那里 generateTerrain(1,terrains);

这是我的主类:

public class MainGameLoop extends JFrame{
    //CREATING THE LOADER
    final static Loader loader = new Loader();

    public static void main(String[] args) {

        //CREATING THE DISPLAY
        DisplayManager.createDisplay();


        //CREATE CAMERA
        Camera camera = new Camera(15f, 5f, 40f);

        //CREATE MASTER RENDERER
        final MasterRenderer renderer = new MasterRenderer();

        //LISTS
        final List<TexturedModel> texturedModels=new ArrayList<TexturedModel>(); 
        final List<Entity> entities=new ArrayList<Entity>();
        final List<Terrain> terrains=new ArrayList<Terrain>(); 

        //Loading the models into the VAOs
        //1
        loadTexturedModel("stall", "stall", texturedModels);
        //2
        loadTexturedModel("dragon", "white", texturedModels);
        //3
        //loadTexturedModel("lowPolyTree", "lowPolyTree", texturedModels, loader);


        //ERSTELLE ENTITIES
        //generateEntity(texturedModels.get(1-1), 15, 0, 15, 0, 180, 0, 1, entities);
        //generateEntity(texturedModels.get(3-1), 5, 0, 5, 0, 0, 0, 1, entities);
        //generateEntity(texturedModels.get(3-1), 23, 0, 8, 0, 90, 0, 0.7f, entities);


        //TEST REFLECTIVITY
        /*
        ModelTexture texture1 = entities.get(0).getModel().getTexture();
        texture1.setReflectivity(10f);
        texture1.setShineDamper(10);
        */

        //CREATE LIGHT
        Light light = new Light(new Vector3f(3000,2000,2000), new Vector3f(2.5f,2.5f,2.5f));

        //CREATE TERRAIN
        //generateTerrain(0, terrains);
        //generateTerrain(1, terrains);

        ////////////////////////////////////////////////////////////////////
        //WORLD EDITOR FENSTER
        ////////////////////////////////////////////////////////////////////

        //ERSTELLE FENSTER
        final JFrame f=new JFrame("Map Editor"); 

        //MENÜLEISTE
        JMenuBar menuBar;

        //MENÜS 
        JMenu fileMenu;         //FileMenu
        JMenu lightTerrainMenu;     //LightTerrain Menu
        JMenu modelMenu;        //ModelMenu

        //MENÜPUNKTE
        JMenuItem createNewWorld;   //New World
        JMenuItem saveWorld;        //Save
        JMenuItem loadWorld;        //Load
        JMenuItem addTree;          //AddTree
        JMenuItem addModel;         //Add Model
        JMenuItem close;            //Quit

        JMenuItem addTerrain;
        JMenuItem addLight;


        //CREATE MENUBAR
        menuBar = new JMenuBar();

        //CREATE MENUS
        fileMenu = new JMenu("File");
        lightTerrainMenu = new JMenu("Terrain/Light");
        modelMenu = new JMenu("Model");

        //CREATE MENUITEMS
        createNewWorld = new JMenuItem("New world");
        saveWorld = new JMenuItem("Save world");
        loadWorld = new JMenuItem("Load world");
        addTree = new JMenuItem("Add tree");
        addModel = new JMenuItem("Add model");
        close = new JMenuItem("Close");

        addTerrain = new JMenuItem("Add terrain");
        addLight = new JMenuItem("Add light");

        //ADD MENU ITEMS
        fileMenu.add(createNewWorld);
        fileMenu.add(saveWorld);
        fileMenu.add(loadWorld);
        fileMenu.add(close);

        lightTerrainMenu.add(addTerrain);
        lightTerrainMenu.add(addLight);

        modelMenu.add(addTree);
        modelMenu.add(addModel);


        //ADD MENUS TO MENU BAR
        menuBar.add(fileMenu);
        menuBar.add(lightTerrainMenu);
        menuBar.add(modelMenu);


        //ADD MENU TO FRAME
        f.add(menuBar, BorderLayout.NORTH);

        //CREATE WINDOW
        f.setSize(400, 300);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);  


        ////////////////////////////////////////////////////////////////////////////////////////////////
        //LISTENER LISTENER LISTENER LISTENER
        ////////////////////////////////////////////////////////////////////////////////////////////////


      //ADDTERRAIN LISTENR
        addTerrain.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {

                final JFrame f2=new JFrame("Add Terrain");
                final JLabel l1 = new JLabel("Terrain can only be: 1x1, 2x2, 3x3...");
                final JLabel l2 = new JLabel("e.g. if you enter 2 it will be a 2x2 terrain");
                Button b1=new Button("Create Terrain"); 
                final TextField tfield = new TextField("", 1);
                l1.setBounds(50, 10, 250, 30);
                l2.setBounds(50, 40, 250, 30);
                tfield.setBounds(50, 70, 130, 30);  
                b1.setBounds(50,100,120,30);  


                b1.addActionListener(new ActionListener(){  
                public void actionPerformed(ActionEvent e){  

                        String input= tfield.getText();
                        generateTerrain(1, terrains);

                }  
                });


                f2.add(b1);
                f2.add(l1);
                f2.add(l2);
                f2.add(tfield);

                f2.setSize(400,300);  
                f2.setLayout(null);

                f2.setVisible(true);

                }

        });

        //ADDMODEL LISTENER
        addModel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                final JFrame f1=new JFrame("Add Model");
                final JLabel l1 = new JLabel("NO MODEL");
                final JLabel l2 = new JLabel("NO TEXTURE");
                l1.setBounds(100, 30, 120, 30);
                l2.setBounds(250, 30, 120, 30);
                /////////////////////////
                //BUTTON ADD MODEL
                /////////////////////////
                Button b1=new Button("Choose model");  
                b1.setBounds(50,100,120,30);  

                b1.addActionListener(new ActionListener(){  
                public void actionPerformed(ActionEvent e){  
                    //CREATE FILE CHOOSER
                    JFileChooser fc = new JFileChooser();
                    FileNameExtensionFilter filter = new FileNameExtensionFilter("Object Dateien", "obj");
                    fc.setFileFilter(filter);
                    int returnVal = fc.showOpenDialog(null);
                    if(returnVal == JFileChooser.APPROVE_OPTION) {
                       System.out.println("You added the following model to your model library: " + fc.getSelectedFile().getName());
                       String currentLine = fc.getSelectedFile().getName();
                       System.out.println(currentLine);

                       String[] parts = currentLine.split("\\.");

                       String part1 = parts[0];
                       l1.setText(part1);
                    }  

                }  
                });

                /////////////////////////
                //BUTTON ADD TEXTURE
                /////////////////////////
                Button b2=new Button("Choose texture");  
                b2.setBounds(200,100,120,30);  

                b2.addActionListener(new ActionListener(){  
                    public void actionPerformed(ActionEvent e){  
                        //CREATE FILE CHOOSER
                        JFileChooser fc = new JFileChooser();
                        FileNameExtensionFilter filter = new FileNameExtensionFilter("Texture Dateien", "png");
                        fc.setFileFilter(filter);
                        int returnVal = fc.showOpenDialog(null);
                        if(returnVal == JFileChooser.APPROVE_OPTION) {
                            System.out.println("You added the following texture to your model: " + fc.getSelectedFile().getName());
                            String currentLine = fc.getSelectedFile().getName();
                            System.out.println(currentLine);

                            String[] parts = currentLine.split("\\.");

                            String part1 = parts[0];
                            l2.setText(part1);
                        }  

                    }  
                });
               Button b3=new Button("Add Model");  
                b3.setBounds(150,150,120,30);  

                b3.addActionListener(new ActionListener(){  
                    public void actionPerformed(ActionEvent e){  

                        l1.getText();
                        l2.getText();
                        //loadTexturedModel("lowPolyTree", "lowPolyTree", texturedModels, loader);
                        }  


                });


                f1.add(b1);
                f1.add(b2);
                f1.add(b3);
                f1.add(l1);
                f1.add(l2);
                f1.setSize(400,300);  
                f1.setLayout(null);

                f1.setVisible(true);

                }
        });
        //ADDTREE LISTENR
        addTree.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                //TREE

                generateEntity(texturedModels.get(3-1), 0, 0, 0, 0, 0, 0, 1, entities);
            }
        });

        //CLOSE LISTENER
        close.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                //Programm schließen

                int result = JOptionPane.showConfirmDialog((Component) null, "Unsaved changes will be lost!","Quit world editor?", JOptionPane.YES_NO_OPTION);
                if(result==0)
                System.exit(0);
            }
        });





        //////////////////////////////////////////////////////////////////////
        ////MAIN GAME LOOP
        /////////////////////////////////////////////////////////////////////
        while(!Display.isCloseRequested()){

            renderer.render(light, camera);
            DisplayManager.updateDisplay();

            camera.move();

            for(Terrain terr:terrains){
                renderer.processTerrain(terr);
            }

            for(Entity ent:entities){
                renderer.processEntity(ent);
            }


        }
        //////////////////////////////////////////////////////////////////////
        ////END MAIN GAME LOOP
        /////////////////////////////////////////////////////////////////////

        //CLEANUP
        renderer.cleanUp();
        loader.cleanUp();
        DisplayManager.closeDisplay();
    }


    public static void loadTexturedModel(String modelName, String textureName, List<TexturedModel> texturedModels){

        texturedModels.add( new TexturedModel(OBJLoader.loadObjModel(modelName,
                loader), new ModelTexture(loader.loadTexture(textureName))));
    }

    public static void generateEntity(TexturedModel model, int posX, int posY, int posZ,
            float rotX, float rotY, float rotZ, float scale, List<Entity> entities){

        entities.add(new Entity(model, new Vector3f(posX,posY,posZ), rotX, rotY, rotZ, scale));
    }
    public static void generateTerrain(int size, List<Terrain> terrains){
        terrains.add(new Terrain(size, 0, loader, new ModelTexture(loader.loadTexture("grass"))));
    }

    public static void genTexturedModel(String name1, String name2, List texturedModels){
        loadTexturedModel("lowPolyTree", "lowPolyTree", texturedModels);
    }



}

最佳答案

首先,要了解实际问题:只有当调用线程中存在 OpenGL 上下文时,才能发出 OpenGL 调用。 OpenGL 使用线程本地存储来跟踪任何线程的当前上下文。您创建的 LWJGL 2 Display 的 OpenGL 上下文将在调用 Display.create() 的线程中处于当前状态,该线程可能位于主线程调用的未公开的 DisplayManager 类中的某个位置。另一方面,AWT(以及在某种程度上的 Swing)使用单独的专用线程来处理窗口消息事件,例如单击按钮,并将使用该线程调用事件回调。并且 LWJGL 显示的 OpenGL 上下文在该 AWT 事件线程中将不是当前的。

我的建议:创建一个渲染命令队列(可能是 java.lang.Runnable 的实例),该队列将被轮询,并且所包含的渲染命令由 LWJGL 显示 OpenGL 上下文当前所在的线程处理,并且有 AWT 回调问题将命令渲染到该队列中。

关于java - 如何将 OpenGL 上下文放入我当前的线程中,未找到 opengl 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49705658/

相关文章:

java - JOOQ:从按 1 列分组的另一个表中选择列

java - DrawElements 无法按预期处理多个对象

java - 从 lambda 对象获取 MethodHandle

Javafx:如果服务消息更新(标签绑定(bind)到消息),标签变为空白

math - 纹理投影+透视校正,数学正确

c++ - 如何在 2D opengl 中进行拾取?

c++ - 复制托管 Silverlight 控件的内容

java - JMonkeyEngine 在 Intel 视频适配器上崩溃

java - LWJGL Javadoc 及其描述?

java - Linux 系统上使用 Java/Eclipse TPTP 进行 16 线程/16 核心代码分析