text:
<file_sep>from pyglet.gl import *
from pyglet import graphics
from pyglet import gl
from pyglet import clock
from pyglet.window import key
import ShaderLoader
from ObjLoader import ObjLoader
from pyrr import Vector3, Vector4, matrix44, Matrix44
from shaders import ObjectShader, ShapeShader, set_shader_camera
import time
import numpy
import random
from DBConnector import *

class Rock:
    ROCK_WIDTH = 3
    instances = []
    instance_locations = []
    db = DBConnector()
    rock_path = db.execute("SELECT path FROM visualpropertypath WHERE name = 'rock'")[0][0]
    del db
    mesh = ObjLoader()
    mesh.load_model(rock_path)
    num_verts = len(mesh.vertex_index)
    texture_offset = len(mesh.vertex_index) * 12
    data = numpy.array(mesh.model, dtype=GLfloat)
    del mesh

    def __init__(self, tekstur):
        Rock.instances.append(self)
        Rock.instance_locations.append([])

        self.vao_rock = GLuint()
        # generate a vertex array object for the rock - the vao
        glGenVertexArrays(1, self.vao_rock)
        # bind the rock's vao
        glBindVertexArray(self.vao_rock)
        # setup the rock's vertex buffer object - the vbo
        vbo_sphere = pyglet.graphics.vertexbuffer.create_buffer(Rock.data.nbytes, GL_ARRAY_BUFFER, GL_STATIC_DRAW)
        vbo_sphere.bind()
        vbo_sphere.set_data(Rock.data.ctypes.data)

        # vertex attribute pointer settings for the rock vbo
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0)
        glEnableVertexAttribArray(0)
        # textures
        glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, Rock.texture_offset)
        glEnableVertexAttribArray(1)

        glBindBuffer(GL_ARRAY_BUFFER, 0)  # unbind the vbo
        glBindVertexArray(0)  # unbind the vao

        # region texture settings
        self.texture = GLuint(0)
        glGenTextures(1, self.texture)
        glBindTexture(GL_TEXTURE_2D, self.texture)
        # set the texture wrapping
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
        # set the texture filtering
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)

        image = pyglet.image.load(tekstur)
        image_data = image.get_data('RGB', image.pitch)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data)
        # endregion

    def render(self, translasi):
        # to draw the rock, we need to rebind the rock's vao
        model_loc = ObjectShader.model_loc
        rock_model = matrix44.create_from_translation(translasi).flatten().astype("float32") #this is the model transformation matrix
        c_rock_model = numpy.ctypeslib.as_ctypes(rock_model)

        glBindVertexArray(self.vao_rock)
        glBindTexture(GL_TEXTURE_2D, self.texture)
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, c_rock_model)
        glDrawArrays(GL_POLYGON, 0, Rock.num_verts)
        glDrawArrays(GL_TRIANGLES, 0, Rock.num_verts)
        glBindVertexArray(0)

    def batch_render(self, list_translasi): # me-render banyak rock dengan tekstur sama
        glBindVertexArray(self.vao_rock)
        glBindTexture(GL_TEXTURE_2D, self.texture)
        model_loc = ObjectShader.model_loc

        for translasi in list_translasi:
            rock_model = matrix44.create_from_translation(Vector3(translasi)).flatten().astype("float32") #this is the model transformation matrix
            c_rock_model = numpy.ctypeslib.as_ctypes(rock_model)
            glUniformMatrix4fv(model_loc, 1, GL_FALSE, c_rock_model)
            glDrawArrays(GL_TRIANGLES, 0, Rock.num_verts)
        glBindVertexArray(0)

    @staticmethod
    def add_instance_location(rocktype, location):
        Rock.instance_locations[rocktype].append(location)

    @staticmethod
    def draw_all_rock():
        for i in range(len(Rock.instances)):
            Rock.instances[i].batch_render(Rock.instance_locations[i])<file_sep>import time
import pyglet
from pyglet import graphics, clock
from pyglet.gl import *
from pyglet.window import *
from pyrr import Vector3, Vector4, matrix44, Matrix44
from Mushrooms import *
from MushroomSquare import *
from MushroomGarden import *
from CouplingPath import *
from Rock import *
import shaders
from shaders import *
from DBConnector import *
import numpy
from GUI import ShroomGUI
import threading

class MyWindow(pyglet.window.Window):
    GROUND_COLOR = [0.0,0.5,0.2,1.0]
    DATABASE_NAME = DBConnector.DATABASE_NAME
    DEFAULT_CAMPOS = [0.0, 25.0, -30.0]
    DEFAULT_CAMLOOKAT = [0.0, 0.0, 0.0]
    DEFAULT_SPEED = 3
    OVERVIEW_SPEED = 6
    # OVERVIEW_CAMPOS = [0.0, 75.0, -20.0]
    # OVERVIEW_CAMLOOKAT = [0.0, 45.0, 0.0]
    DEF_TO_OVERVIEW = (Vector3([0.0, 50.0, 10.0]), Vector3([0.0, 45.0, 0.0]))
    camPos = Vector3([0.0, 25.0, -30.0])
    camLookAt = Vector3([0.0, 0.0, 0.0])
    camSpeed = 3
    SHROOM_READ_DIST = 35
    SQR_READ_DIST = 70
    GARD_READ_DIST = 150
    #interface_width = part to the left of the screen to use

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.keys = key.KeyStateHandler()
        self.push_handlers(self.keys)
        self.interface_width = self.width//5

        #self.set_minimum_size(400, 300)
        glClearColor(0.0, 0.6, 0.8, 0.0)
        glEnable(GL_LINE_SMOOTH)
        glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE)
        #setup 2d drawing
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluOrtho2D(0, self.width, 0, self.height)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        self.interface = ShroomGUI(self.width, self.height, self.interface_width, self)
        ShapeShader.init(self.camPos, self.width/self.height)
        ObjectShader.init(self.camPos, self.width/self.height)

        self.mushrooms = []
        self.init_textures(MyWindow.DATABASE_NAME)

        self.rocks = []
        self.rocks.append(Rock('textures/rocktexture.jpg'))
        self.fences = []
        self.fences.append(Fence('textures/woodtexture.jpg'))

        self.gardens, new_pos = self.create_from_database(MyWindow.DATABASE_NAME)

        clock.schedule_interval(self.update, 1.0/30)

        self.selected_object = None
        self.overview_mode = False
        self.frame_counter = 0

        if self.gardens:
            # new_pos = (self.gardens[0].position + self.gardens[-1].position + [self.gardens[-1].width, 0, 0])/2 + [0, 25, 0]
            self.camPos = new_pos
            self.camLookAt = self.camPos + [0, -25, 30]
            self.on_key_press(key.T, None)

    def rotateCam(self, axis, dtheta):
        rotation_mat = matrix44.create_from_axis_rotation(axis, dtheta)
        self.camLookAt -= self.camPos
        newvec = Vector4.from_vector3(self.camLookAt, 1.0)
        newvec = rotation_mat.dot(newvec)
        self.camLookAt = Vector3.from_vector4(newvec)[0]
        self.camLookAt += self.camPos

    def update(self,dt, changed=False):
        self.frame_counter = (self.frame_counter + 1)%10

        if self.keys[key.W]:    #forward
            self.camPos[2] += self.camSpeed
            self.camLookAt[2] += self.camSpeed
            changed = True
        elif self.keys[key.S]:  #backward
            self.camPos[2] -= self.camSpeed
            self.camLookAt[2] -= self.camSpeed
            changed = True
        elif self.keys[key.D]:  #left
            self.camPos[0] -= self.camSpeed
            self.camLookAt[0] -= self.camSpeed
            changed = True
        elif self.keys[key.A]:  #right
            self.camPos[0] += self.camSpeed
            self.camLookAt[0] += self.camSpeed
            changed = True
        elif self.keys[key.Q] and not self.overview_mode: # going down
            if self.camPos[1] > 3: # don't go too low
                self.camPos[1] -= self.camSpeed
                self.camLookAt[1] -= self.camSpeed
                changed = True
        elif self.keys[key.E] and not self.overview_mode: # going up
            self.camPos[1] += self.camSpeed
            self.camLookAt[1] += self.camSpeed
            changed = True
        # else:  # uncomment this section to enable looking up and looking down
        #     direction = self.camLookAt - self.camPos
            # turning_limit = direction[2] < 1
            # if self.keys[key.Z] and not (turning_limit and direction[1]>0):
            #     self.rotateCam([1.0,0.0,0.0],0.1)
            #     changed = True
            # elif self.keys[key.C] and not (turning_limit and direction[1]<0):
            #     self.rotateCam([1.0,0.0,0.0],-0.1)
            #     changed = True

        if changed:    #update camera
            set_shader_camera(self.camPos, self.camLookAt[:3])
            readable_shroom = [sh for sh in Mushroom.get_all_shroom_position() if distance_3d(sh, self.camPos) < self.SHROOM_READ_DIST]
            Mushroom.set_readable(readable_shroom)
            MushroomSquare.set_readable_to_campos(self.camPos, self.SQR_READ_DIST)
            Garden.set_readable_to_campos(self.camPos, self.GARD_READ_DIST)

    def on_key_press(self, symbol, modifiers):
        if symbol == key.T: #toggle overview mode (camera looking down from a high place)
            self.camPos += self.DEF_TO_OVERVIEW[0] if not self.overview_mode else -self.DEF_TO_OVERVIEW[0]
            self.camLookAt += self.DEF_TO_OVERVIEW[1] if not self.overview_mode else -self.DEF_TO_OVERVIEW[1]
            self.camSpeed = self.OVERVIEW_SPEED if not self.overview_mode else self.DEFAULT_SPEED
            self.overview_mode = self.overview_mode == False
        elif symbol == key.R:   #reset camera to starting position
            self.camPos = Vector3(self.DEFAULT_CAMPOS)
            self.camLookAt = Vector3(self.DEFAULT_CAMLOOKAT)
            self.camSpeed = self.DEFAULT_SPEED
            self.overview_mode = False
        elif symbol == key.ESCAPE:
            self.close()
        self.update(1.0/30, True)

    def on_draw(self):
        self.clear()
        #3d mode
        # shapes
        glEnable(GL_DEPTH_TEST)

        glUseProgram(ShapeShader.shader)
        ShapeShader.use_color(self.GROUND_COLOR)
        graphics.vertex_list(4, ('v3f',(
            self.camPos[0] + 500.0, -0.1, self.camPos[2] + 500.0,
            self.camPos[0] + 500.0, -0.1, self.camPos[2] - 500.0,
            self.camPos[0] - 500.0, -0.1, self.camPos[2] - 500.0,
            self.camPos[0] - 500.0, -0.1, self.camPos[2] + 500.0
        ))
        ).draw(GL_QUADS) #draw the ground

        if self.frame_counter < 5:
            undraw_detected = False
        elif self.frame_counter < 10:
            undraw_detected = True

        for gard in self.gardens:
            gard.draw_garden(undraw_detected=undraw_detected)

        ## objects
        glUseProgram(ObjectShader.shader)
        Mushroom.draw_all_shroom(undraw_detected=undraw_detected)
        Rock.draw_all_rock()

        #2d
        glDisable(GL_DEPTH_TEST)
        glUseProgram(0)
        # MushroomSquare.draw_all_warning_sign()
        MushroomSquare.draw_all_readable_names()
        MushroomSquare.draw_all_family_numbers()
        # Garden.draw_all_warning_sign()
        Garden.draw_all_readable_names()
        self.interface.draw()

    def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
        if x < self.interface_width:
            self.interface.GUI_scroll(x, y, scroll_x, scroll_y)

    def on_mouse_press(self, x, y, button, modifiers):
        # render selection codes
        glUseProgram(ShapeShader.shader)
        if x >= self.interface_width:   # a click on 3d world
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
            MushroomSquare.draw_all_selectable()

            # read pixel at x,y
            rgb = (GLubyte * 4)(0)
            glReadPixels(x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, rgb)

            # the code from read pixels is the object selectable ID (currently only squareID as only squares are selectable)
            # set selected_object to it if code exist in square instances, else set to None
            rgbcode = rgb[0] * 256 + rgb[1]
            if self.selected_object is not None:
                self.selected_object.set_unselect()
                self.selected_object = None
            if rgbcode in MushroomSquare.instances:
                self.selected_object = MushroomSquare.instances[rgbcode]
                self.selected_object.set_selected()
        else:   # let GUI handle clicks on GUI
            self.interface.GUI_click(x,y)

    def init_textures(self, database):
        db = DBConnector(database)
        textures = db.execute('SELECT * FROM visualpropertypath WHERE type = "shroom texture"')
        db_name_map = {
            'RedField': 'rf',
            'RedMethod': 'rm',
            'YellowField': 'yf',
            'YellowMethod': 'ym',
            'BlueField': 'bf',
            'BlueMethod': 'bm',
            'GreenField': 'gf',
            'GreenMethod': 'gm'}
        threads = []
        for text in textures:
            if text[1] not in db_name_map:
                continue
            else:
                # def parallel_create_Mushroom(outputlist, name, code):
                #     outputlist.append(Mushroom(name, code))
                # threads.append(GeneralThread(parallel_create_Mushroom, self.mushrooms, text[3], db_name_map[text[1]]))
                # threads[-1].start()
                code = db_name_map[text[1]]
                loop = 3 if code[1] == 'm' else 1
                for i in range(loop):
                    self.mushrooms.append(Mushroom(text[3], code, i))
        # for t in threads:
        #     t.join()
        # print(self.mushrooms)

    def create_from_database(self, database):
        gardens = []
        squares = {}
        db = DBConnector(database)
        project = db.execute("SELECT * from project")
        self.interface.set_title(project[0][2])
        del project
        methods = db.execute('SELECT * from method')
        fields = db.execute('SELECT * from field')
        refs = db.execute('SELECT * from reference')
        packs = db.execute('SELECT * FROM package')
        inherit = db.execute('SELECT * from inheritancerelationship')
        coupling = db.execute('SELECT * from couplingrelationship')
        packinpack = db.execute('SELECT * from packageinpackage')
        map_db_names = {'concrete class':'br', 'abstract class':'b', 'interface':'g', 'private':'r', 'default':'y', 'protected':'b', 'public':'g'}
        # create packages (garden)
        supermostgardens = []

        packTree = packageTree(packs, packinpack) #create package dependency tree
        packs = packTree.topological_sort() #sort tree to a list

        for pack in packs:
            packparent = packTree.get_parent_id(pack[0])
            if packparent is None:
                move = 0 if supermostgardens == [] else supermostgardens[-1].position[0] + supermostgardens[-1].width + 10
                newgard = Garden(pack[0], pack[1], [move, 0.0, 0.0])
                gardens.append(newgard)
                supermostgardens.append(newgard)
            else:
                newgard = Garden.instances[packparent].create_subgarden(pack[0], pack[1])
                gardens.append(newgard)

            #create squares
            for ref in refs:
                if ref[1] == pack[0]: #asumsi ref[1] dan packs[i][0] is Package_id
                    sq = gardens[-1].create_square(ref[0], ref[2], map_db_names[ref[3]])
                    squares[ref[0]] = sq
                    #fill square with shrooms
                    for method in methods:
                        if method[1] == ref[0]: # inReference == ref.elementid
                            size = '0' if method[4] <= 10 else ('1' if method[4]<=30 else '2')
                            stype = map_db_names[method[3]] + 'm' + size
                            sq.add_shroom(method[0], method[2], stype, False)
                    for field in fields:
                        if field[1] == ref[0]:
                            stype = map_db_names[field[3]] + 'f0'
                            sq.add_shroom(field[0], field[2], stype, True)
                    sq.reset_shape()
            gardens[-1].reset_shape()
        # set square child and coupling
        for rel in inherit:
            child = rel[0]
            parent = rel[1]
            if parent in squares:
                squares[parent].add_child(squares[child])
        for rel in coupling:
            if rel[0] in squares:
                squares[rel[0]].add_coupling(squares[rel[1]])
        #clean db results
        del methods, fields, refs, packs, inherit, coupling, packinpack

        # add GUI elements
        project = db.execute('SELECT * FROM project')
        detectors = db.execute('SELECT * FROM detectionstrategy')
        detected_method = db.execute('SELECT * FROM detectedmethod')
        detected_reference = db.execute('SELECT * FROM detectedreference')
        detected_package = db.execute('SELECT * FROM detectedpackage')
        # log = db.execute('SELECT * from history')
        #set score
        self.interface.set_score(project[0][3])
        #set strategies
        self.interface.create_detection_strategies(detectors, detected_method, detected_reference, detected_package)

        starting_campos = (supermostgardens[-1].position + supermostgardens[0].position + [supermostgardens[-1].width, 50, 0])/2
        return gardens, starting_campos

class packageTree:
    def __init__(self, packages, pack_in_pack):
        self.nodes = {}
        # self.superpackages = {}

        self.create_nodes(packages)
        self.make_tree(pack_in_pack)

    def create_nodes(self, packages):
        for pack in packages:
            self.nodes[pack[0]] = packageNode(pack[0], pack)

    def make_tree(self, pack_in_pack):
        for pip in pack_in_pack:
            # self.superpackages[pip[0]] = pip[1]
            if pip[0] in self.nodes:
                container = pip[1]
                contained = pip[0]
                self.nodes[container].child.append(self.nodes[contained])
                self.nodes[contained].parent = self.nodes[container]

    def get_parent_id(self, pack_id):
        if pack_id in self.nodes:
            if self.nodes[pack_id].parent is not None:
                return self.nodes[pack_id].parent.id
        return None

    def topological_sort(self):
        sortedlist = []
        for node in self.nodes:
            if self.nodes[node].level() == 0:
                self.nodes[node].top_sort(sortedlist)
        return sortedlist
        # temp = sorted([self.nodes[k] for k in self.nodes], key=lambda x:x.level())
        # return [node.value for node in temp]

class packageNode:
    def __init__(self, id, value):
        self.id = id
        self.value = value
        self.parent = None
        self.child = []

    def level(self):
        if self.parent is None:
            return 0
        else:
            return self.parent.level()+1

    def top_sort(self, outputlist):
        outputlist.append(self.value)
        for child in self.child:
            child.top_sort(outputlist)

if __name__ == "__main__":
    screen = pyglet.canvas.get_display().get_default_screen()
    width = screen.width
    height = screen.height
    ShaderAttributes.set_screen_size(width, height)
    window = MyWindow(screen=screen, fullscreen=True)
    pyglet.app.run()<file_sep>from pyglet.gl import *
from pyglet import *
import ShaderLoader
from ObjLoader import ObjLoader
from pyrr import Vector3, Vector4, matrix44, Matrix44
import numpy

class ShaderAttributes:
    FOVY = 65.0 #degrees field of view
    NEAR_CLIP = 0.1
    FAR_CLIP = 400.0
    WIDTH = 1280.0
    HEIGHT = 720.0
    ASPECT_RATIO = 1280.0 / 720

    @staticmethod
    def set_screen_size(width, height):
        SA = ShaderAttributes
        SA.WIDTH = width
        SA.HEIGHT = height
        SA.ASPECT_RATIO = width / height
        projection_matrix = matrix44.create_perspective_projection_matrix(SA.FOVY, SA.ASPECT_RATIO, SA.NEAR_CLIP, SA.FAR_CLIP)
        ShapeShader.projection = projection_matrix
        ObjectShader.projection = projection_matrix

SA = ShaderAttributes

def set_shader_camera(position, lookAt):
    view = matrix44.create_look_at(position, lookAt, ObjectShader.cameraUp)
    ShapeShader.vp = matrix44.multiply(view, ObjectShader.projection)
    c_vp = numpy.ctypeslib.as_ctypes(ShapeShader.vp.flatten().astype("float32"))
    glUseProgram(ObjectShader.shader)
    glUniformMatrix4fv(ObjectShader.vp_loc, 1, GL_FALSE, c_vp)
    glUseProgram(ShapeShader.shader)
    glUniformMatrix4fv(ShapeShader.vp_loc, 1, GL_FALSE, c_vp)

def set_2d_mode():
    glUseProgram(0)
    glDisable(GL_DEPTH_TEST)

def unset_2d_mode(shader):
    glEnable(GL_DEPTH_TEST)
    glUseProgram(shader)

def distance_3d(coor1, coor2):
    return sum((coor1-coor2)**2)**0.5

def convert_3dcoor_to_screen(coor):
    screenpos = matrix44.apply_to_vector(ShapeShader.vp, Vector4.from_vector3(coor, 1.0))
    if screenpos[3] == 0:
        screenpos[3] += 0.01
    screenpos = screenpos/screenpos[3]
    #if screenpos[0] < -1 or screenpos[0] > 1 or screenpos[1] < -1 or screenpos[1] > 1:
    #    return [-10,-10]
    screenpos = [(screenpos[0]+1)*SA.WIDTH//2, (screenpos[1]+1)*SA.HEIGHT//2]
    return screenpos

class ObjectShader:
    shader = None
    #shape_shader = None
    cameraUp = numpy.array([0.0, 1.0, 0.0], dtype='float')
    projection = None
    vp_loc = None
    model_loc = None

    @staticmethod
    def init(position = Vector3([0.0,0.0,-5.0]), aspect_ratio = SA.ASPECT_RATIO):
        ObjectShader.projection = matrix44.create_perspective_projection_matrix(SA.FOVY, aspect_ratio, SA.NEAR_CLIP, SA.FAR_CLIP)
        if ObjectShader.shader is None:
            ObjectShader.create_shader()
            ObjectShader.vp_loc = glGetUniformLocation(ObjectShader.shader, b"vp")
            ObjectShader.model_loc = glGetUniformLocation(ObjectShader.shader, b"model")
            ObjectShader.create_perspective_projection(position)

    @staticmethod
    def create_shader():
        ObjectShader.shader = ShaderLoader.compile_shader("shaders/object_vert.glsl", "shaders/object_frag.glsl")
        #ObjectShader.shape_shader = ShaderLoader.compile_shader("shaders/shape_vert.glsl", "shaders/shape_frag.glsl")
        glUseProgram(ObjectShader.shader)

    @staticmethod
    def create_perspective_projection(position, lookAt = Vector3([0,0,0])):
        view = matrix44.create_look_at(position, lookAt, ObjectShader.cameraUp)
        vp = matrix44.multiply(view, ObjectShader.projection).flatten().astype("float32")
        c_vp = numpy.ctypeslib.as_ctypes(vp)
        glUniformMatrix4fv(ObjectShader.vp_loc, 1, GL_FALSE, c_vp)

class ShapeShader:
    shader = None
    cameraUp = numpy.array([0.0, 1.0, 0.0], dtype='float')
    projection = None
    vp_loc = None
    col_loc = None
    vp = None
    used_color = [0.0, 0.0, 0.0, 0.0]

    @staticmethod
    def init(position = Vector3([0.0,0.0,-5.0]), aspect_ratio= SA.ASPECT_RATIO):
        ShapeShader.projection = matrix44.create_perspective_projection_matrix(SA.FOVY, aspect_ratio, SA.NEAR_CLIP, SA.FAR_CLIP)
        if ShapeShader.shader is None:
            ShapeShader.create_shader()
            ShapeShader.vp_loc = glGetUniformLocation(ShapeShader.shader, b"vp")
            ShapeShader.col_loc = glGetUniformLocation(ShapeShader.shader, b"vColor")
            ShapeShader.create_perspective_projection(position)

    @staticmethod
    def create_shader():
        ShapeShader.shader = ShaderLoader.compile_shader("shaders/shape_vert.glsl", "shaders/shape_frag.glsl")
        glUseProgram(ShapeShader.shader)

    @staticmethod
    def create_perspective_projection(position, lookAt = Vector3([0,0,0])):
        view = matrix44.create_look_at(position, lookAt, ShapeShader.cameraUp)
        ShapeShader.vp = matrix44.multiply(view, ShapeShader.projection)
        c_vp = numpy.ctypeslib.as_ctypes(ShapeShader.vp.flatten().astype("float32"))
        glUniformMatrix4fv(ShapeShader.vp_loc, 1, GL_FALSE, c_vp)

    @staticmethod
    def use_color(color):
        ShapeShader.used_color = color
        col = Vector4(color).flatten().astype('float32')
        c_col = numpy.ctypeslib.as_ctypes(col)
        glUniform4fv(ShapeShader.col_loc, 1, c_col)

    @staticmethod
    def draw(gl_mode, vert_list, color):
        pass #! to be implemented

    <file_sep>package controller;

import java.io.IOException;

public class PythonController {
	public PythonController() throws IOException{
		runPython();
	}
	public void runPython() throws IOException{
		String path="cmd /c start C:\\xampp\\htdocs\\codevis-MushroomFarm\\test.bat";
		Runtime rn=Runtime.getRuntime();
		Process pr=rn.exec(path);
	}
}
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.8.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 05, 2019 at 09:16 AM
-- Server version: 10.1.31-MariaDB
-- PHP Version: 7.2.4

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `mushroom_farm`
--

-- --------------------------------------------------------

--
-- Table structure for table `couplingrelationship`
--

DROP TABLE IF EXISTS `couplingrelationship`;
CREATE TABLE `couplingrelationship` (
  `referenceId` int(11) NOT NULL,
  `coupledReferenceId` int(11) NOT NULL,
  `coupledReferenceName` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `couplingrelationship`
--

INSERT INTO `couplingrelationship` (`referenceId`, `coupledReferenceId`, `coupledReferenceName`) VALUES
(1, 2, 'DAO'),
(4, 2, 'DAO'),
(5, 2, 'DAO'),
(5, 8, 'ProjectDAO'),
(6, 3, 'DAOMetric'),
(7, 3, 'DAOMetric'),
(8, 2, 'DAO'),
(9, 3, 'DAOMetric');

-- --------------------------------------------------------

--
-- Table structure for table `detectedmethod`
--

DROP TABLE IF EXISTS `detectedmethod`;
CREATE TABLE `detectedmethod` (
  `methodId` int(11) NOT NULL,
  `strategyId` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `detectedmethod`
--

INSERT INTO `detectedmethod` (`methodId`, `strategyId`) VALUES
(1, 4),
(18, 4);

-- --------------------------------------------------------

--
-- Table structure for table `detectedpackage`
--

DROP TABLE IF EXISTS `detectedpackage`;
CREATE TABLE `detectedpackage` (
  `packageId` int(11) NOT NULL,
  `strategyId` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `detectedreference`
--

DROP TABLE IF EXISTS `detectedreference`;
CREATE TABLE `detectedreference` (
  `referenceId` int(11) NOT NULL,
  `strategyId` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `detectedreference`
--

INSERT INTO `detectedreference` (`referenceId`, `strategyId`) VALUES
(1, 3),
(6, 2),
(8, 5);

-- --------------------------------------------------------

--
-- Table structure for table `detectionstrategy`
--

DROP TABLE IF EXISTS `detectionstrategy`;
CREATE TABLE `detectionstrategy` (
  `strategyId` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `type` enum('method','reference','package') NOT NULL,
  `strategy` varchar(256) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `detectionstrategy`
--

INSERT INTO `detectionstrategy` (`strategyId`, `name`, `type`, `strategy`) VALUES
(1, 'Data class', 'reference', 'NSC <= threshold AND DIT <= threshold AND NOF > threshold'),
(2, 'Feature Envy', 'reference', 'LCOM >= threshold'),
(3, 'Large Class', 'reference', 'LCOM >= threshold AND WMC >= threshold AND NOF >= threshold AND NEOM >= threshold'),
(4, 'Long Method', 'method', 'MLOC >= threshold AND VG >= threshold AND NBD >= threshold'),
(5, 'Refused Bequest', 'reference', 'SIX >= threshold');

-- --------------------------------------------------------

--
-- Table structure for table `field`
--

DROP TABLE IF EXISTS `field`;
CREATE TABLE `field` (
  `fieldId` int(11) NOT NULL,
  `referenceId` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `accessModifier` enum('private','default','protected','public') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;

--
-- Dumping data for table `field`
--

INSERT INTO `field` (`fieldId`, `referenceId`, `name`, `accessModifier`) VALUES
(1, 10, 'id', 'private'),
(2, 10, 'artifact', 'private'),
(3, 10, 'metric', 'private'),
(4, 10, 'subject', 'protected'),
(5, 10, 'message', 'protected'),
(6, 10, 'date', 'protected');

-- --------------------------------------------------------

--
-- Table structure for table `inheritancerelationship`
--

DROP TABLE IF EXISTS `inheritancerelationship`;
CREATE TABLE `inheritancerelationship` (
  `child` int(11) NOT NULL,
  `parent` int(11) NOT NULL,
  `parentName` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `inheritancerelationship`
--

INSERT INTO `inheritancerelationship` (`child`, `parent`, `parentName`) VALUES
(3, 2, 'DAO');

-- --------------------------------------------------------

--
-- Table structure for table `method`
--

DROP TABLE IF EXISTS `method`;
CREATE TABLE `method` (
  `methodId` int(11) NOT NULL,
  `referenceId` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `accessModifier` enum('private','default','protected','public') NOT NULL,
  `mloc` decimal(10,0) NOT NULL,
  `nbd` decimal(10,0) NOT NULL,
  `par` decimal(10,0) NOT NULL,
  `vg` decimal(10,0) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;

--
-- Dumping data for table `method`
--

INSERT INTO `method` (`methodId`, `referenceId`, `name`, `accessModifier`, `mloc`, `nbd`, `par`, `vg`) VALUES
(1, 1, 'register', 'public', '9', '0', '0', '0'),
(2, 1, 'getLastID', 'private', '14', '0', '0', '0'),
(3, 1, 'register', 'public', '22', '0', '0', '0'),
(4, 1, 'registerCycleData', 'public', '34', '0', '0', '0'),
(5, 1, 'update', 'public', '55', '0', '0', '0'),
(6, 1, 'selectAll', 'public', '0', '0', '0', '0'),
(7, 1, 'selectById', 'public', '0', '0', '0', '0'),
(8, 1, 'removeCycleDataByIdProject', 'public', '0', '0', '0', '0'),
(9, 1, 'removeCycleByIdProject', 'public', '0', '0', '0', '0'),
(10, 2, 'register', 'public', '0', '0', '0', '0'),
(11, 2, 'update', 'public', '0', '0', '0', '0'),
(12, 2, 'selectAll', 'public', '0', '0', '0', '0'),
(13, 2, 'selectById', 'public', '0', '0', '0', '0'),
(14, 3, 'selectByObject', 'public', '0', '0', '0', '0'),
(15, 3, 'applyDetectionStrategy', 'public', '0', '0', '0', '0'),
(16, 3, 'totalArtifacts', 'public', '0', '0', '0', '0'),
(17, 4, 'register', 'public', '0', '0', '0', '0'),
(18, 4, 'update', 'public', '0', '0', '0', '0'),
(19, 4, 'delete', 'public', '0', '0', '0', '0'),
(20, 4, 'selectAll', 'public', '0', '0', '0', '0'),
(21, 4, 'selectById', 'public', '0', '0', '0', '0'),
(22, 4, 'selectDetectionStrategiesByFilter', 'public', '0', '0', '0', '0'),
(23, 4, 'createSqlFilter', 'private', '0', '0', '0', '0'),
(24, 4, 'remove', 'public', '0', '0', '0', '0'),
(25, 4, 'selectAllAllowed', 'public', '0', '0', '0', '0'),
(26, 5, 'register', 'public', '0', '0', '0', '0'),
(27, 5, 'update', 'public', '0', '0', '0', '0'),
(28, 5, 'selectAll', 'public', '0', '0', '0', '0'),
(29, 5, 'selectById', 'public', '0', '0', '0', '0'),
(30, 5, 'getInformationSource', 'private', '0', '0', '0', '0'),
(31, 5, 'getInformationArtifact', 'private', '0', '0', '0', '0'),
(32, 5, 'selectLogsByFilter', 'public', '0', '0', '0', '0'),
(33, 5, 'createSqlFilter', 'private', '0', '0', '0', '0'),
(34, 5, 'removeByIdProject', 'public', '0', '0', '0', '0'),
(35, 6, 'selectByObject', 'public', '0', '0', '0', '0'),
(36, 6, 'register', 'public', '0', '0', '0', '0'),
(37, 6, 'update', 'public', '0', '0', '0', '0'),
(38, 6, 'selectAll', 'public', '0', '0', '0', '0'),
(39, 6, 'selectById', 'public', '0', '0', '0', '0'),
(40, 6, 'createQuerySelectByObject', 'private', '0', '0', '0', '0'),
(41, 6, 'assignAttributeInQuery', 'private', '0', '0', '0', '0'),
(42, 6, 'applyDetectionStrategy', 'public', '0', '0', '0', '0'),
(43, 6, 'totalArtifacts', 'public', '0', '0', '0', '0'),
(44, 6, 'removeByIdProject', 'public', '0', '0', '0', '0'),
(45, 7, 'register', 'public', '0', '0', '0', '0'),
(46, 7, 'update', 'public', '0', '0', '0', '0'),
(47, 7, 'selectAll', 'public', '0', '0', '0', '0'),
(48, 7, 'selectById', 'public', '0', '0', '0', '0'),
(49, 7, 'selectByObject', 'public', '0', '0', '0', '0'),
(50, 7, 'createQuerySelectByObject', 'private', '0', '0', '0', '0'),
(51, 7, 'assignAttributeInQuery', 'private', '0', '0', '0', '0'),
(52, 7, 'applyDetectionStrategy', 'public', '0', '0', '0', '0'),
(53, 7, 'totalArtifacts', 'public', '0', '0', '0', '0'),
(54, 7, 'removeByIdProject', 'public', '0', '0', '0', '0'),
(55, 8, 'register', 'public', '0', '0', '0', '0'),
(56, 8, 'getLastID', 'public', '0', '0', '0', '0'),
(57, 8, 'register', 'public', '0', '0', '0', '0'),
(58, 8, 'selectMetricsProject', 'public', '0', '0', '0', '0'),
(59, 8, 'registerMetricProject', 'public', '0', '0', '0', '0'),
(60, 8, 'updateMetricProject', 'public', '0', '0', '0', '0'),
(61, 8, 'update', 'public', '0', '0', '0', '0'),
(62, 8, 'remove', 'public', '0', '0', '0', '0'),
(63, 8, 'removeMeasureProjectByIdProject', 'public', '0', '0', '0', '0'),
(64, 8, 'removeProject', 'private', '0', '0', '0', '0'),
(65, 8, 'selectAll', 'public', '0', '0', '0', '0'),
(66, 8, 'selectById', 'public', '0', '0', '0', '0'),
(67, 8, 'selectProjectsByFilter', 'public', '0', '0', '0', '0'),
(68, 8, 'createSqlFilter', 'private', '0', '0', '0', '0'),
(69, 9, 'selectByObject', 'public', '0', '0', '0', '0'),
(70, 9, 'register', 'public', '0', '0', '0', '0'),
(71, 9, 'update', 'public', '0', '0', '0', '0'),
(72, 9, 'selectAll', 'public', '0', '0', '0', '0'),
(73, 9, 'selectById', 'public', '0', '0', '0', '0'),
(74, 9, 'createQuerySelectByObject', 'private', '0', '0', '0', '0'),
(75, 9, 'assignAttributeInQuery', 'private', '0', '0', '0', '0'),
(76, 9, 'applyDetectionStrategy', 'public', '0', '0', '0', '0'),
(77, 9, 'totalArtifacts', 'public', '0', '0', '0', '0'),
(78, 9, 'removeByIdProject', 'public', '0', '0', '0', '0'),
(79, 10, 'writeLogCharacterInvalid', 'public', '0', '0', '0', '0'),
(80, 10, 'printLog', 'public', '0', '0', '0', '0'),
(81, 10, 'getMetric', 'public', '0', '0', '0', '0'),
(82, 10, 'getSubject', 'public', '0', '0', '0', '0'),
(83, 10, 'getArtifact', 'public', '0', '0', '0', '0'),
(84, 10, 'getMessage', 'public', '0', '0', '0', '0'),
(85, 10, 'getDate', 'public', '0', '0', '0', '0'),
(86, 10, 'getId', 'public', '0', '0', '0', '0');

-- --------------------------------------------------------

--
-- Table structure for table `methodmetricvalue`
--

DROP TABLE IF EXISTS `methodmetricvalue`;
CREATE TABLE `methodmetricvalue` (
  `methodId` int(11) NOT NULL,
  `metricId` int(11) NOT NULL,
  `value` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `metric`
--

DROP TABLE IF EXISTS `metric`;
CREATE TABLE `metric` (
  `metricId` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `type` enum('method','reference','package') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;

-- --------------------------------------------------------

--
-- Table structure for table `package`
--

DROP TABLE IF EXISTS `package`;
CREATE TABLE `package` (
  `packageId` int(11) NOT NULL,
  `name` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;

--
-- Dumping data for table `package`
--

INSERT INTO `package` (`packageId`, `name`) VALUES
(1, 'structure.dao'),
(2, 'structure'),
(3, 'structure.log');

-- --------------------------------------------------------

--
-- Table structure for table `packageinpackage`
--

DROP TABLE IF EXISTS `packageinpackage`;
CREATE TABLE `packageinpackage` (
  `packageId` int(11) NOT NULL,
  `container` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `packageinpackage`
--

INSERT INTO `packageinpackage` (`packageId`, `container`) VALUES
(1, 2),
(3, 2);

-- --------------------------------------------------------

--
-- Table structure for table `packagemetricvalue`
--

DROP TABLE IF EXISTS `packagemetricvalue`;
CREATE TABLE `packagemetricvalue` (
  `packageId` int(11) NOT NULL,
  `metricId` int(11) NOT NULL,
  `value` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `project`
--

DROP TABLE IF EXISTS `project`;
CREATE TABLE `project` (
  `projectId` int(11) NOT NULL,
  `path` varchar(100) NOT NULL,
  `name` varchar(100) NOT NULL,
  `freeSmellCodePercentage` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;

--
-- Dumping data for table `project`
--

INSERT INTO `project` (`projectId`, `path`, `name`, `freeSmellCodePercentage`) VALUES
(1, 'C:\\Users\\A456UQ\\workspace_anandhini\\FindSmells-master.zip', 'FindSmells-master', 88);

-- --------------------------------------------------------

--
-- Table structure for table `reference`
--

DROP TABLE IF EXISTS `reference`;
CREATE TABLE `reference` (
  `referenceId` int(11) NOT NULL,
  `packageId` int(11) DEFAULT NULL,
  `name` varchar(100) NOT NULL,
  `type` enum('interface','abstract class','concrete class') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;

--
-- Dumping data for table `reference`
--

INSERT INTO `reference` (`referenceId`, `packageId`, `name`, `type`) VALUES
(1, 1, 'CycleDAO', 'concrete class'),
(2, 1, 'DAO', 'interface'),
(3, 1, 'DAOMetric', 'interface'),
(4, 1, 'DetectionStrategyDAO', 'concrete class'),
(5, 1, 'LogDAO', 'concrete class'),
(6, 1, 'MethodDAO', 'concrete class'),
(7, 1, 'PackageDAO', 'concrete class'),
(8, 1, 'ProjectDAO', 'concrete class'),
(9, 1, 'TypeDAO', 'concrete class'),
(10, 3, 'Log', 'concrete class');

-- --------------------------------------------------------

--
-- Table structure for table `referencemetricvalue`
--

DROP TABLE IF EXISTS `referencemetricvalue`;
CREATE TABLE `referencemetricvalue` (
  `referenceId` int(11) NOT NULL,
  `metricId` int(11) NOT NULL,
  `value` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `visualpropertypath`
--

DROP TABLE IF EXISTS `visualpropertypath`;
CREATE TABLE `visualpropertypath` (
  `pathId` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `type` varchar(256) NOT NULL,
  `path` varchar(256) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;

--
-- Dumping data for table `visualpropertypath`
--

INSERT INTO `visualpropertypath` (`pathId`, `name`, `type`, `path`) VALUES
(1, 'mushroom', 'model', 'objects/smallMushroom.obj'),
(2, 'rock', 'model', 'objects/rock.obj'),
(3, 'fence', 'model', 'objects/fence.obj'),
(4, 'RedField', 'shroom texture', 'textures/RedField.jpg'),
(5, 'RedMethod', 'shroom texture', 'textures/RedMethod.jpg'),
(6, 'YellowField', 'shroom texture', 'textures/YellowField.jpg'),
(7, 'YellowMethod', 'shroom texture', 'textures/YellowMethod.jpg'),
(8, 'BlueField', 'shroom texture', 'textures/BlueField.jpg'),
(9, 'BlueMethod', 'shroom texture', 'textures/BlueMethod.jpg'),
(10, 'GreenField', 'shroom texture', 'textures/GreenField.jpg'),
(11, 'GreenMethod', 'shroom texture', 'textures/GreenMethod.jpg'),
(12, 'score', 'gui texture', 'textures/score.jpg'),
(13, 'checkbox empty', 'gui texture', 'textures/box-s.png'),
(14, 'checkbox checked', 'gui texture', 'textures/checkedbox-s.png'),
(15, 'rock', 'texture', 'textures/rocktexture.jpg'),
(16, 'wood', 'texture', 'textures/woodtexture.jpg'),
(17, 'medMushroom', 'model', 'objects/mediumMushroom.obj'),
(18, 'larMushroom', 'model', 'objects/largeMushroom.obj');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `couplingrelationship`
--
ALTER TABLE `couplingrelationship`
  ADD KEY `referenceId` (`referenceId`),
  ADD KEY `coupledWith` (`coupledReferenceId`);

--
-- Indexes for table `detectedmethod`
--
ALTER TABLE `detectedmethod`
  ADD KEY `strategyId` (`strategyId`),
  ADD KEY `methodId` (`methodId`);

--
-- Indexes for table `detectedreference`
--
ALTER TABLE `detectedreference`
  ADD KEY `referenceId` (`referenceId`),
  ADD KEY `strategyId` (`strategyId`);

--
-- Indexes for table `detectionstrategy`
--
ALTER TABLE `detectionstrategy`
  ADD PRIMARY KEY (`strategyId`);

--
-- Indexes for table `field`
--
ALTER TABLE `field`
  ADD PRIMARY KEY (`fieldId`),
  ADD KEY `inClass` (`referenceId`);

--
-- Indexes for table `inheritancerelationship`
--
ALTER TABLE `inheritancerelationship`
  ADD KEY `ChildClass` (`child`),
  ADD KEY `ParentClass` (`parent`);

--
-- Indexes for table `method`
--
ALTER TABLE `method`
  ADD PRIMARY KEY (`methodId`),
  ADD KEY `inReference` (`referenceId`);

--
-- Indexes for table `metric`
--
ALTER TABLE `metric`
  ADD PRIMARY KEY (`metricId`);

--
-- Indexes for table `package`
--
ALTER TABLE `package`
  ADD PRIMARY KEY (`packageId`);

--
-- Indexes for table `packageinpackage`
--
ALTER TABLE `packageinpackage`
  ADD KEY `packageId` (`packageId`),
  ADD KEY `container` (`container`);

--
-- Indexes for table `packagemetricvalue`
--
ALTER TABLE `packagemetricvalue`
  ADD KEY `packagemetricvalue_ibfk_1` (`packageId`),
  ADD KEY `metricId` (`metricId`);

--
-- Indexes for table `project`
--
ALTER TABLE `project`
  ADD PRIMARY KEY (`projectId`);

--
-- Indexes for table `reference`
--
ALTER TABLE `reference`
  ADD PRIMARY KEY (`referenceId`),
  ADD KEY `inPackage` (`packageId`);

--
-- Indexes for table `visualpropertypath`
--
ALTER TABLE `visualpropertypath`
  ADD PRIMARY KEY (`pathId`),
  ADD KEY `path` (`path`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `detectionstrategy`
--
ALTER TABLE `detectionstrategy`
  MODIFY `strategyId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;

--
-- AUTO_INCREMENT for table `field`
--
ALTER TABLE `field`
  MODIFY `fieldId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;

--
-- AUTO_INCREMENT for table `method`
--
ALTER TABLE `method`
  MODIFY `methodId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=87;

--
-- AUTO_INCREMENT for table `metric`
--
ALTER TABLE `metric`
  MODIFY `metricId` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `package`
--
ALTER TABLE `package`
  MODIFY `packageId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

--
-- AUTO_INCREMENT for table `project`
--
ALTER TABLE `project`
  MODIFY `projectId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

--
-- AUTO_INCREMENT for table `reference`
--
ALTER TABLE `reference`
  MODIFY `referenceId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;

--
-- AUTO_INCREMENT for table `visualpropertypath`
--
ALTER TABLE `visualpropertypath`
  MODIFY `pathId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19;

--
-- Constraints for dumped tables
--

--
-- Constraints for table `couplingrelationship`
--
ALTER TABLE `couplingrelationship`
  ADD CONSTRAINT `couplingrelationship_ibfk_1` FOREIGN KEY (`referenceId`) REFERENCES `reference` (`referenceId`),
  ADD CONSTRAINT `couplingrelationship_ibfk_2` FOREIGN KEY (`coupledReferenceId`) REFERENCES `reference` (`referenceId`);

--
-- Constraints for table `detectedmethod`
--
ALTER TABLE `detectedmethod`
  ADD CONSTRAINT `detectedmethod_ibfk_2` FOREIGN KEY (`strategyId`) REFERENCES `detectionstrategy` (`strategyId`),
  ADD CONSTRAINT `detectedmethod_ibfk_3` FOREIGN KEY (`methodId`) REFERENCES `method` (`methodId`);

--
-- Constraints for table `detectedreference`
--
ALTER TABLE `detectedreference`
  ADD CONSTRAINT `detectedreference_ibfk_1` FOREIGN KEY (`referenceId`) REFERENCES `reference` (`referenceId`),
  ADD CONSTRAINT `detectedreference_ibfk_2` FOREIGN KEY (`strategyId`) REFERENCES `detectionstrategy` (`strategyId`);

--
-- Constraints for table `field`
--
ALTER TABLE `field`
  ADD CONSTRAINT `field_ibfk_1` FOREIGN KEY (`referenceId`) REFERENCES `reference` (`referenceId`);

--
-- Constraints for table `inheritancerelationship`
--
ALTER TABLE `inheritancerelationship`
  ADD CONSTRAINT `inheritancerelationship_ibfk_1` FOREIGN KEY (`child`) REFERENCES `reference` (`referenceId`),
  ADD CONSTRAINT `inheritancerelationship_ibfk_2` FOREIGN KEY (`parent`) REFERENCES `reference` (`referenceId`);

--
-- Constraints for table `method`
--
ALTER TABLE `method`
  ADD CONSTRAINT `method_ibfk_1` FOREIGN KEY (`referenceId`) REFERENCES `reference` (`referenceId`);

--
-- Constraints for table `packageinpackage`
--
ALTER TABLE `packageinpackage`
  ADD CONSTRAINT `packageinpackage_ibfk_1` FOREIGN KEY (`packageId`) REFERENCES `package` (`packageId`),
  ADD CONSTRAINT `packageinpackage_ibfk_2` FOREIGN KEY (`container`) REFERENCES `package` (`packageId`);

--
-- Constraints for table `packagemetricvalue`
--
ALTER TABLE `packagemetricvalue`
  ADD CONSTRAINT `packagemetricvalue_ibfk_1` FOREIGN KEY (`packageId`) REFERENCES `package` (`packageId`),
  ADD CONSTRAINT `packagemetricvalue_ibfk_2` FOREIGN KEY (`metricId`) REFERENCES `metric` (`metricId`);

--
-- Constraints for table `reference`
--
ALTER TABLE `reference`
  ADD CONSTRAINT `reference_ibfk_1` FOREIGN KEY (`packageId`) REFERENCES `package` (`packageId`);
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>from Mushrooms import *
from pyglet import text
from shaders import *
from Rock import *
import math

class MushroomSquare:
    BROWN_SQUARE_COLOR = [0.38, 0.2, 0.07,1.0]
    BROWN_SQUARE_SELECTED = [0.58, 0.4, 0.2,1.0]
    GREEN_SQUARE_COLOR = [0.0, 0.7, 0.3, 1.0]
    GREEN_SQUARE_SELECTED = [0.0, 0.9, 0.4,1.0]
    INTERSHROOM_DISTANCE = 11.0
    ROW_SHROOM_NUM = 5
    MAX_SQR_WIDTH = INTERSHROOM_DISTANCE * (ROW_SHROOM_NUM + 1)
    MAX_SQR_HEIGHT = MAX_SQR_WIDTH
    # states of a mushroomsquare: 0:unselected, 1:selected, 2:related to selected object
    #squareid = 0
    instances = {}
    detected_instances = []
    readable_instances = []
    tcolor = {'b':BROWN_SQUARE_COLOR, 'b1':BROWN_SQUARE_SELECTED, 'g':GREEN_SQUARE_COLOR, 'g1':GREEN_SQUARE_SELECTED} # map types to square color, xxx1 : color when selected
    # sqtypes = tanah hijau/coklat, dikelilingi batu/tidak
    def __init__(self, sq_id, sq_name, sq_type, position, width=6, height=6):
        #MushroomSquare.squareid += 1
        self.id = sq_id
        MushroomSquare.instances[self.id] = self
        self.type = sq_type[0]
        self.has_rock_fence = 'r' in sq_type
        self.name = sq_name
        self.width = width
        self.height = height
        self.position = Vector3(position) #top left corner of the square
        pad = MushroomSquare.INTERSHROOM_DISTANCE
        self.next_coordinate = [position[0]+pad, position[1], position[2]+pad]
        self.next_col = 0
        #self.shrooms = [] #field shroom
         # list of mushrooms coordinates
        self.parent = [] #list of mushroomsquare ids
        self.child = [] #list of mushroomsquare ids
        self.coupling = [] #list of mushroomsquare ids

        self.state = 0
        maxnum = MushroomSquare.ROW_SHROOM_NUM
        dist = MushroomSquare.INTERSHROOM_DISTANCE
        self.next_shroom_vec = Vector3([dist, 0.0, 0.0])
        self.m_shroom_rows = [ObjectRow(Vector3(self.next_coordinate), maxnum, self.next_shroom_vec)]
        self.f_shroom_rows = [ObjectRow(Vector3(self.next_coordinate) + Vector3([0.0, 0.0, 0.0]), maxnum, self.next_shroom_vec)]
        # self.f_shroom_rows = [ObjectRow(Vector3(self.next_coordinate) + Vector3([0.0, 0.0, dist]), maxnum, self.next_shroom_vec)]
        self.set_drawn_square(position, MushroomSquare.MAX_SQR_WIDTH, height)
        # self.__update_next_coordinate()
        # self.detected = False
        #self.interdim = Interdimensionals()
        # self.reset_shape()

    def add_child(self, square):
        self.child.append(square)
        square.parent.append(self)

    def del_child(self, square):
        if square in self.child:
            square.parent.remove(self)
            self.child.remove(square)

    def add_coupling(self, square):
        self.coupling.append(square)
        square.coupling.append(self)

    def is_unselected(self):
        return self.state == 0

    def is_selected(self):
        return self.state == 1

    def is_related(self):
        return self.state == 2

    def set_selected(self):
        if self.type[-1] != '1':
            self.type += '1'
        self.state = 1
        #self.set_draw_family_label()
        for id in self.parent:
            if type(id) == int:
                MushroomSquare.instances[id].set_related()
            else:
                id.set_related()
        for id in self.child:
            if type(id) == int:
               MushroomSquare.instances[id].set_related()
            else:
                id.set_related()

    def set_unselect(self):
        #self.set_undraw_family_label()
        if self.type[-1] == '1':
            self.type = self.type[:-1]
        if self.state != 0:
            self.state = 0
            for id in self.parent:
                if type(id) == int:
                    MushroomSquare.instances[id].set_unselect()
                else:
                    id.set_unselect()
            for id in self.child:
                if type(id) == int:
                    MushroomSquare.instances[id].set_unselect()
                else:
                    id.set_unselect()

    def set_related(self):
        self.state = 2
        #self.set_draw_family_label()
        for parent in self.parent:
            if parent.is_unselected():
                parent.set_related()
        for child in self.child:
            if child.is_unselected():
                child.set_related()

    def set_drawn_square(self, position=None, width=None, height=None):
        if width is None:
            width = self.width
        else:
            self.width = width
        if height is None:
            height = self.height
        else:
            self.height = height
        if position is None:
            position = self.position
        else:
            move_vector = Vector3(position) - self.position
            self.position += move_vector
            self.shift_shroom_positions(move_vector)

        self.vertices = graphics.vertex_list(4, ('v3f',(
            position[0], position[1], position[2],
            position[0]+width, position[1], position[2],
            position[0]+width, position[1], position[2]+height,
            position[0], position[1], position[2]+height
        )))
        if self.has_rock_fence:
            self.__set_rock_fence()

    def reset_shape(self):
        newheight = 0
        newheight += len(self.f_shroom_rows) if len(self.f_shroom_rows[-1].obj_positions)>0 else len(self.f_shroom_rows)-1
        newheight += len(self.m_shroom_rows) if len(self.m_shroom_rows[-1].obj_positions)>0 else len(self.m_shroom_rows)-1
        newheight *= MushroomSquare.INTERSHROOM_DISTANCE
        newheight += MushroomSquare.INTERSHROOM_DISTANCE
        self.set_drawn_square(height=newheight)

    def __update_next_coordinate(self):
        self.next_coordinate[2] += MushroomSquare.INTERSHROOM_DISTANCE
        #self.set_drawn_square(height=self.height+MushroomSquare.INTERSHROOM_DISTANCE)

    def add_shroom(self, shroom_id, shroom_name, shroom_type, is_field=False, auto_reset=False, size=0):
        newshroom = Vector3([0.0,0.0,0.0])
        dist = MushroomSquare.INTERSHROOM_DISTANCE
        maxnum = MushroomSquare.ROW_SHROOM_NUM
        in_front = is_field
        if not in_front: #the "not" here is a rough patch to switch fornt row and back row
            if self.f_shroom_rows[-1].is_full():
                self.__update_next_coordinate()
                new_coor = Vector3(self.next_coordinate)
                self.f_shroom_rows.append(ObjectRow(new_coor, maxnum, self.next_shroom_vec))
            newshroom = self.f_shroom_rows[-1].add_object(newshroom, shroom_id)
        else:
            if len(self.m_shroom_rows) == 1 and self.m_shroom_rows[0].is_empty():
                shift_vec = Vector3([0.0, 0.0, dist])
                for row in self.f_shroom_rows:
                    row.shift_row(shift_vec, not in_front)
            elif self.m_shroom_rows[-1].is_full():
                self.__update_next_coordinate()
                next_coor = Vector3([0.0,0.0,0.0]) + self.f_shroom_rows[0].position
                shift_vec = Vector3([0.0, 0.0, dist])
                for row in self.f_shroom_rows:
                    row.shift_row(shift_vec, not in_front)
                self.m_shroom_rows.append(ObjectRow(next_coor, maxnum, self.next_shroom_vec))
            newshroom = self.m_shroom_rows[-1].add_object(newshroom, shroom_id)
        #self.shrooms.append(newshroom)
        Mushroom.add_instance_detail(shroom_id, shroom_name, shroom_type, newshroom, is_field)

        if auto_reset:
            self.reset_shape()
        return newshroom

    def shift_shroom_positions(self, move_vector):
        for row in self.f_shroom_rows:
            row.shift_row(move_vector, True)
        for row in self.m_shroom_rows:
            row.shift_row(move_vector, False)

    def draw(self, colorcode = None, undraw_detected=False):
        #self.update_labels()
        if colorcode is not None:
            code1 = (colorcode // 256) / 255.0
            code2 = (colorcode % 256) / 255.0
            ShapeShader.use_color([code1, code2, 0.0, 0.0])
        else:
            ShapeShader.use_color(MushroomSquare.tcolor[self.type])

        if self.id not in MushroomSquare.detected_instances or not undraw_detected:
            self.vertices.draw(GL_QUADS)
            if self.has_rock_fence:
                self.__draw_rock_fence()
        # if self.state != 0:
        #     self.__draw_family_label()

        # if self.detected:
        #     self.__draw_warning_sign()

    def get_family_number(self):
        if len(self.parent) == 0:
            return 1
        else:
            return self.parent[0].get_family_number()+1

    def __draw_family_label(self):
        fam_num = self.get_family_number()
        # get screen position of square corner
        screenpos = convert_3dcoor_to_screen(self.position)

        #draw 2D
        set_2d_mode()
        graphics.vertex_list(4, ('v2f', (
            screenpos[0],screenpos[1],
            screenpos[0], screenpos[1]+25,
            screenpos[0]+25,screenpos[1]+25,
            screenpos[0]+25, screenpos[1]
        )), ('c3B', (50,50,250, 50,50,250, 50,50,250,  50,50,250))).draw(GL_QUADS)
        text.Label(' '+str(fam_num), font_size=18, color=[0,0,0,255], x = screenpos[0], y=screenpos[1], anchor_x='left', anchor_y='bottom').draw()
        unset_2d_mode(ShapeShader.shader)

    def __draw_name_label(self):
        screenpos = convert_3dcoor_to_screen(self.position+ [self.width//2,0,0])
        #draw in 2d
        set_2d_mode()
        name_length = len(self.name)
        name_text = text.Label(self.name, font_size=18, color=[0,0,0,255], x = screenpos[0], y=screenpos[1], anchor_x='center', anchor_y='bottom')
        graphics.vertex_list(4, ('v2f', (
            screenpos[0]-name_text.content_width//2-2,screenpos[1],
            screenpos[0]-name_text.content_width//2-2, screenpos[1]+25,
            screenpos[0]+name_text.content_width//2+2,screenpos[1]+25,
            screenpos[0]+name_text.content_width//2+2, screenpos[1]
        )), ('c3B', (200,200,200, 200,200,200,  200,200,200,  200,200,200))).draw(GL_QUADS)
        graphics.vertex_list(4, ('v2f', (
            screenpos[0]-name_text.content_width//2-2,screenpos[1],
            screenpos[0]-name_text.content_width//2-2, screenpos[1]+25,
            screenpos[0]+name_text.content_width//2+2,screenpos[1]+25,
            screenpos[0]+name_text.content_width//2+2, screenpos[1]
        )), ('c3B', (0,0,0, 0,0,0,  0,0,0,  0,0,0))).draw(GL_LINE_LOOP)
        name_text.draw()
        unset_2d_mode(ShapeShader.shader)

    def __draw_warning_sign(self):
        screenpos = convert_3dcoor_to_screen(self.position + [self.width,0,0])
        # draw in 2d
        set_2d_mode()
        graphics.vertex_list(3, ('v2f', (
            screenpos[0], screenpos[1],
            screenpos[0]+36, screenpos[1],
            screenpos[0]+18, screenpos[1]+36
        )), ('c3B', (
            255,255,0, 255,255,0, 255,255,0
        ))).draw(GL_TRIANGLES)
        text.Label('!', font_size=18, color=[0,0,0,255], x=screenpos[0]+14, y=screenpos[1], anchor_x='left', anchor_y='bottom').draw()
        unset_2d_mode(ShapeShader.shader)

    #### """

    def __set_rock_fence(self):
        hori_rocks_num = round(self.width//Rock.ROCK_WIDTH)
        verti_rocks_num = round(self.height//Rock.ROCK_WIDTH)+1
        hori_space = self.width/hori_rocks_num
        verti_space = self.height/verti_rocks_num
        self.rock_coors = []
        for i in range(hori_rocks_num):
            pos1 = self.position + Vector3([(1+i)*hori_space, 0.0, 0.0])
            pos2 = self.position + Vector3([i*hori_space, 0.0, self.height])
            self.rock_coors.append(pos1)
            self.rock_coors.append(pos2)
        for i in range(verti_rocks_num):
            pos1 = self.position + Vector3([0.0, 0.0, i*verti_space])
            pos2 = self.position + Vector3([self.width, 0.0, (1+i)*verti_space])
            self.rock_coors.append(pos1)
            self.rock_coors.append(pos2)

    def __draw_rock_fence(self):
        glUseProgram(ObjectShader.shader)
        Rock.instances[0].batch_render(self.rock_coors)
        glUseProgram(ShapeShader.shader)

    @staticmethod
    def draw_all_selectable():
        for key in MushroomSquare.instances:
            MushroomSquare.instances[key].draw(colorcode = key)

    @staticmethod
    def set_detected(square_ids):
        MushroomSquare.detected_instances = square_ids
        # for square in square_ids:
        #     if square in MushroomSquare.instances and square not in MushroomSquare.detected_instances:
        #         MushroomSquare.detected_instances.append(square)

    # @staticmethod
    # def unset_detected(square_ids):
    #     for square in square_ids:
    #         if square in MushroomSquare.instances and square in MushroomSquare.detected_instances:
    #             MushroomSquare.detected_instances.remove(square)

    @staticmethod
    def draw_all_warning_sign():
        set_2d_mode()
        for square in reversed(list(MushroomSquare.detected_instances)):
            MushroomSquare.instances[square].__draw_warning_sign()
        unset_2d_mode(ShapeShader.shader)

    @staticmethod
    def set_readable_to_campos(cam_pos, read_dist):
        MushroomSquare.readable_instances = []
        for square in MushroomSquare.instances:
            sqr_dist = distance_3d(cam_pos, MushroomSquare.instances[square].position)
            if sqr_dist < read_dist:
                MushroomSquare.readable_instances.append(square)

    @staticmethod
    def draw_all_readable_names():
        set_2d_mode()
        for square in reversed(list(MushroomSquare.readable_instances)):
            MushroomSquare.instances[square].__draw_name_label()
        unset_2d_mode(ShapeShader.shader)

    @staticmethod
    def draw_all_family_numbers():
        set_2d_mode()
        for square in reversed(list(MushroomSquare.instances)):
            if MushroomSquare.instances[square].state != 0:
                MushroomSquare.instances[square].__draw_family_label()
        unset_2d_mode(ShapeShader.shader)

class ObjectRow:
    def __init__(self, position, max_object, obj_displacement):
        self.position = position
        self.obj_positions = []
        self.indexed_obj = {}
        self.max = max_object
        self.obj_disp = obj_displacement # a Vector3 displacement

    def get_next_position(self):
        if len(self.obj_positions) > 0:
            prev_pos = self.obj_positions[-1]
            return Vector3([0.0,0.0,0.0]) + prev_pos + self.obj_disp
        else:
            return self.position

    def add_object(self, obj_position, obj_id=None):
        if self.is_full():
            return False
        next_pos = self.get_next_position()
        obj_position[0] = next_pos[0]
        obj_position[1] = next_pos[1]
        obj_position[2] = next_pos[2]
        self.obj_positions.append(obj_position)

        if obj_id:
            self.indexed_obj[obj_id]= next_pos
            # print(list(self.indexed_obj))
        return next_pos

    def shift_row(self, vector, is_field):
        # self.position += vector
        for id in self.indexed_obj:
            Mushroom.move_shroom(id, is_field, vector)
        # for obj_pos in self.obj_positions:
        #     obj_pos += vector

    def is_full(self):
        return self.max == len(self.obj_positions)

    def is_empty(self):
        return 0 == len(self.obj_positions)<file_sep>#version 330
in layout(location = 0) vec3 position;

uniform mat4 vp;
uniform mat4 model;

void main()
{
    gl_Position = vp *  vec4(position, 1.0f);
}
<file_sep>"""import pyglet
from pyglet.gl import *
from pyglet import *
from pyglet.window import *

import tinyblend as blend
import pyshaders as shaders
from pyglbuffers import Buffer
from pyrr import Vector3, Vector4, matrix44, Matrix44

class MyWindow(Window):
    def __init__(self, width, height, title=''):
        super(MyWindow, self).__init__(width, height, title)
        glClearColor(0, 0, 0, 1)
        glEnable(GL_DEPTH_TEST)
        self.shader = shaders.from_files_names('shaders/shape_vert.glsl', 'shaders/shape_frag.glsl')
        self.shader.use()
        self.shader.enable_all_attributes()
        self.shader.owned = False
        shaders.transpose_matrices(False)
        self.upload_uniforms()
        self.cubevertices = graphics.vertex_list_indexed(8,
                    [0,1,2,3,   0,1,5,4,    1,2,6,5,    2,3,7,6,    3,0,4,7,    4,5,6,7], # make 6 quads
                    ('v3f', (
                        50,50,50,   #0
                        50,-50,50,  #1
                        -50,-50,50, #2
                        -50,50,50,  #3
                        50,50,-50,  #4
                        50,-50,-50, #5
                        -50,-50,-50,#6
                        -50,50,-50  #7
                    )), ('c3B', (
                        255,0,0,
                        255,255,255,
                        0,0,255,
                        0,255,0,
                        255,255,0,
                        0,255,255,
                        255,0,255,
                        25,25,25
                    ))
                )

    def upload_uniforms(self):
        unif = self.shader.uniforms
        unif.vp = Matrix44.

    def on_draw(self):
        self.clear()
        self.cubevertices.draw(GL_QUADS)

WINDOW = 400
if __name__ == '__main__':
   MyWindow(WINDOW, WINDOW, 'Pyglet Colored Cube')
   pyglet.app.run()
"""

from shaders import *
from pyglet import *
from pyglet.gl import *
from pyglet.window import key
from pyrr import Vector3, Vector4, matrix44, Matrix44

class MyWindow(window.Window):

    def __init__(self, width, height, title=''):
        super(MyWindow, self).__init__(width, height, title)
        self.keys = key.KeyStateHandler()
        self.push_handlers(self.keys)
        gl.glClearColor(0, 0, 0, 1)
        gl.glEnable(gl.GL_DEPTH_TEST)
        ShapeShader.init(Vector3([-5.0,-5.0,-5.0]))
        self.vl = graphics.vertex_list(4, ('v3f',(
            1000.0, 3.0, 1000.0,
            1000.0, 3.0, -1000.0,
            -1000.0, -3.0, -1000.0,
            -1000.0, -3.0, 1000.0
        ))
        #,('c3B', (130,0,0,130,0,0,130,0,0,130,0,0))
        )

    def on_draw(self):
        self.clear()
        self.vl.draw(GL_QUADS)

WINDOW = 400
if __name__ == '__main__':
   MyWindow(WINDOW, WINDOW, 'Pyglet Colored Cube')
   pyglet.app.run()<file_sep>from pyglet.gl import *
from pyglet import graphics
from pyglet import gl
from pyglet import clock
from pyglet.window import key
import ShaderLoader
from ObjLoader import ObjLoader
from pyrr import Vector3, Vector4, matrix44, Matrix44
from shaders import ObjectShader, ShapeShader, set_shader_camera
import time
import numpy
import random
from DBConnector import *

class Fence:
    FENCE_WIDTH = 3
    instances = []
    h_instance_locations = []
    v_instance_locations = []
    db = DBConnector()
    fence_path = db.execute("SELECT path FROM visualpropertypath WHERE name = 'fence'")[0][0]
    del db
    mesh = ObjLoader()
    mesh.load_model(fence_path)
    num_verts = len(mesh.vertex_index)
    texture_offset = len(mesh.vertex_index) * 12
    data = numpy.array(mesh.model, dtype=GLfloat)
    del mesh

    def __init__(self, tekstur):
        Fence.instances.append(self)
        Fence.h_instance_locations.append([])
        Fence.v_instance_locations.append([])

        self.vao_fence = GLuint()
        # generate a vertex array object for the fence - the vao
        glGenVertexArrays(1, self.vao_fence)
        # bind the fence's vao
        glBindVertexArray(self.vao_fence)
        # setup the fence's vertex buffer object - the vbo
        vbo_sphere = pyglet.graphics.vertexbuffer.create_buffer(Fence.data.nbytes, GL_ARRAY_BUFFER, GL_STATIC_DRAW)
        vbo_sphere.bind()
        vbo_sphere.set_data(Fence.data.ctypes.data)

        # vertex attribute pointer settings for the fence vbo
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0)
        glEnableVertexAttribArray(0)
        # textures
        glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, Fence.texture_offset)
        glEnableVertexAttribArray(1)

        glBindBuffer(GL_ARRAY_BUFFER, 0)  # unbind the vbo
        glBindVertexArray(0)  # unbind the vao

        # region texture settings
        self.texture = GLuint(0)
        glGenTextures(1, self.texture)
        glBindTexture(GL_TEXTURE_2D, self.texture)
        # set the texture wrapping
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
        # set the texture filtering
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)

        image = pyglet.image.load(tekstur)
        image_data = image.get_data('RGB', image.pitch)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data)
        # endregion

    def render(self, translasi):
        # to draw the fence, we need to rebind the fence's vao
        model_loc = ObjectShader.model_loc
        fence_model = matrix44.create_from_translation(translasi).flatten().astype("float32") #this is the model transformation matrix
        c_fence_model = numpy.ctypeslib.as_ctypes(fence_model)

        glBindVertexArray(self.vao_fence)
        glBindTexture(GL_TEXTURE_2D, self.texture)
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, c_fence_model)
        glDrawArrays(GL_POLYGON, 0, Fence.num_verts)
        glDrawArrays(GL_TRIANGLES, 0, Fence.num_verts)
        glBindVertexArray(0)

    def batch_render(self, list_translasi, vertical=True): # me-render banyak fence dengan tekstur sama
        glBindVertexArray(self.vao_fence)
        glBindTexture(GL_TEXTURE_2D, self.texture)
        model_loc = ObjectShader.model_loc
        if not vertical:
            rotate = matrix44.create_from_y_rotation(numpy.pi/2) # 90 degree rotation

        for translasi in list_translasi:
            fence_model = matrix44.create_from_translation(Vector3(translasi)) #this is the model transformation matrix
            if not vertical:
                fence_model = matrix44.multiply(rotate, fence_model)
            c_fence_model = numpy.ctypeslib.as_ctypes(fence_model.flatten().astype('float32'))
            glUniformMatrix4fv(model_loc, 1, GL_FALSE, c_fence_model)
            glDrawArrays(GL_TRIANGLES, 0, Fence.num_verts)
        glBindVertexArray(0)

    @staticmethod
    def add_instance_location(fencetype, location, vertical=True):
        if vertical:
            Fence.v_instance_locations[fencetype].append(location)
        else:
            Fence.h_instance_locations[fencetype].append(location)

    @staticmethod
    def draw_all_fence():
        for i in range(len(Fence.instances)):
            Fence.instances[i].batch_render(Fence.h_instance_locations[i], False)
            Fence.instances[i].batch_render(Fence.v_instance_locations[i])<file_sep>package model;

import java.sql.Connection;
import java.sql.DriverManager;

import javax.swing.JOptionPane;

public class DBConnection {

	public Connection getConnection(){
		Connection myConn = null;
		try{
			String url = "jdbc:mysql://localhost:3306/mushroom_farm?useUnicode=true&characterEncoding=UTF-8";
			String user = "root";
			String pwd = "";
			myConn = DriverManager.getConnection(url, user, pwd);
		}catch(Exception e){
			JOptionPane.showMessageDialog(null, "Error connection");
		}
		return myConn;
	}
}
<file_sep>from Mushrooms import *
from MushroomSquare import *
from CouplingPath import *
from Fence import *

class Garden:
    #PATH_WIDTH = 4.0 # width of path connecting mushroomsquares
    INTRSQR_DIST = 13.0 #distance between mushroomsquares
    SQR_DISP = MushroomSquare.MAX_SQR_WIDTH + INTRSQR_DIST
    ROW_SQR_NUM = 2 # amount of mushroomsquares to be located in a row before making a new row
    instances = {}
    readable_instances = []
    def __init__(self, id, name, position, supergarden = None):
        Garden.instances[id] = self
        self.name = name
        self.position = Vector3(position)
        self.squares = []
        self.supergarden = supergarden
        self.subgardens = []
        self.next_sqr_coor = [position[0]+Garden.INTRSQR_DIST*1.5, position[1], position[2]+Garden.INTRSQR_DIST*1.5]
        self.rows = [GardenRow(self.next_sqr_coor, Garden.ROW_SQR_NUM, Vector3([Garden.SQR_DISP, 0.0, 0.0]))]
        self.reset_shape()
        #self.row_count = 0
        self.paths = CouplingPath()
        self.detected = False

    def reset_shape(self):
        squares = self.squares
        subgardens = self.subgardens
        row_widths = [row.get_row_width() for row in self.rows]
        subgard_widths = [sg.width for sg in self.subgardens]
        normalwidth = max(row_widths+subgard_widths) + 2.5 * Garden.INTRSQR_DIST

        self.width = float(normalwidth)

        self.height = ((2+len(squares)//Garden.ROW_SQR_NUM + len(subgardens))*Garden.INTRSQR_DIST +
            sum([row.get_row_height() for row in self.rows]) +
            sum([sg.height for sg in subgardens]))
        self.__set_fences()
        if self.supergarden is not None:
            self.supergarden.reset_shape()

    def set_garden_position(self, position):
        move_vector = position - self.position
        self.position += move_vector
        self.paths.shift_paths(move_vector)
        for gard in self.subgardens:
            gard.set_garden_position(gard.position + move_vector)
        for row in self.rows:
            row.shift_row(move_vector)

    def __update_next_coor(self):
        # fills next_sqr_coor a NEW vector3 containing next position
        if not self.rows[-1].is_full():
            self.next_sqr_coor = list(self.rows[-1].get_next_position())
        else:
            self.next_sqr_coor = list(self.rows[-1].position + [0,0,self.rows[-1].get_row_height() + Garden.INTRSQR_DIST])
            self.rows.append(GardenRow(self.next_sqr_coor, Garden.ROW_SQR_NUM, Vector3([Garden.SQR_DISP, 0.0, 0.0])))

    def create_square(self, ref_id, ref_name, ref_type, autoreset=False):
        #self.row_count += 1
        self.__update_next_coor()
        new_sqr = MushroomSquare(ref_id, ref_name, ref_type, self.next_sqr_coor)
        self.squares.append(new_sqr)
        self.rows[-1].add_square(new_sqr)

        ### path making
        # add path node containing the square
        datanode = self.paths.add_node(new_sqr.position+Vector3([0.0,0.0,0.0]), new_sqr)
        self.paths.add_edge(datanode, new_sqr.position+Vector3([0.0, 0.0, -5.0]))
        # add path node connecting to previous paths
        if len(self.rows[-1].row_objects) == 1: #if first node in row
            if len(self.rows) != 1: # not first row in garden
                #vertical_shift = MushroomSquare.MAX_SQR_HEIGHT + Garden.INTRSQR_DIST
                self.paths.add_edge(new_sqr.position+Vector3([-10.0, 0.0, -5.0]), self.rows[-2].position+Vector3([-10.0, 0.0, -5.0]))
            self.paths.add_edge(new_sqr.position+Vector3([0.0, 0.0, -5.0]), new_sqr.position+Vector3([-10.0, 0.0, -5.0]))
        else:
            prev_coor = self.rows[-1].row_objects[-2].position
            self.paths.add_edge(new_sqr.position+Vector3([0.0, 0.0, -5.0]), Vector3(prev_coor)+Vector3([0.0,0.0,-5.0]))
        ### end path making

        if autoreset:
            self.reset_shape() #adjust garden shape to fit new square
        return new_sqr

    def count_sub_level(self):
        if self.subgardens == []:
            return 0
        else:
            return max([gard.count_sub_level() for gard in self.subgardens]) + 1

    def create_subgarden(self, id, name):
        if self.subgardens == []:
            self.next_sqr_coor = list(self.rows[-1].position + [0,0,self.rows[-1].get_row_height() + Garden.INTRSQR_DIST])
        else:
            self.next_sqr_coor = list(self.subgardens[-1].position + [0,0,self.subgardens[-1].height + Garden.INTRSQR_DIST])
        # self.rows.append(GardenRow(self.next_sqr_coor, 1, Vector3([Garden.SQR_DISP, 0.0, 0.0])))

        subgarden = Garden(id, name, self.next_sqr_coor, supergarden=self)
        self.subgardens.append(subgarden)
        # self.rows[-1].row_objects.append(subgarden)
        return subgarden

    def draw_garden(self, debug=False, undraw_detected=False):
        if debug:
            self.paths.draw(None,None,debug)
        sel = next((x for x in self.squares if x.state == 1), None)
        if sel is not None:
            couplings = [(sel, couple) for couple in sel.coupling]
            self.paths.draw_all_paths(couplings)
            # for couple in sel.coupling:
            #     self.paths.draw(sel, couple)

        for square in self.squares:
            square.draw(undraw_detected=undraw_detected)
        if not self.detected or not undraw_detected:
            self.draw_fences()
        if sel is not None:
            self.__draw_name_label()
            sel._MushroomSquare__draw_name_label()

    def calculate_fences(self):
        coor1 = self.position + Vector3([0,0,0])
        coor2 = self.position + Vector3([self.width, 0, 0])
        coor3 = self.position + Vector3([self.width, 0, self.height])
        coor4 = self.position + Vector3([0, 0, self.height])
        return [coor1,coor2,coor3,coor4] # calculate the 4 points to draw the fences

    def __set_fences(self):
        hori_fence_num = round(self.width//Fence.FENCE_WIDTH)
        verti_fence_num = round(self.height//Fence.FENCE_WIDTH)+1
        hori_space = self.width/hori_fence_num
        verti_space = self.height/verti_fence_num
        self.v_fence_coors = []
        self.h_fence_coors = []
        for i in range(hori_fence_num):
            pos1 = self.position + Vector3([(i)*hori_space, 0.0, 0.0])
            pos2 = self.position + Vector3([i*hori_space, 0.0, self.height])
            self.h_fence_coors.append(pos1)
            self.h_fence_coors.append(pos2)
        for i in range(verti_fence_num):
            pos1 = self.position + Vector3([0.0, 0.0, i*verti_space])
            pos2 = self.position + Vector3([self.width, 0.0, (i)*verti_space])
            self.v_fence_coors.append(pos1)
            self.v_fence_coors.append(pos2)

    def draw_fences(self):
        glUseProgram(ObjectShader.shader)
        Fence.instances[0].batch_render(self.v_fence_coors, True)
        Fence.instances[0].batch_render(self.h_fence_coors, False)
        glUseProgram(ShapeShader.shader)

    def __draw_warning_sign(self):
        screenpos = convert_3dcoor_to_screen(self.position + [self.width,0,0])
        # draw in 2d
        set_2d_mode()
        graphics.vertex_list(3, ('v2f', (
            screenpos[0], screenpos[1],
            screenpos[0]+36, screenpos[1],
            screenpos[0]+18, screenpos[1]+36
        )), ('c3B', (
            255,255,0, 255,255,0, 255,255,0
        ))).draw(GL_TRIANGLES)
        text.Label('!', font_size=18, color=[0,0,0,255], x=screenpos[0]+14, y=screenpos[1], anchor_x='left', anchor_y='bottom').draw()
        unset_2d_mode(ShapeShader.shader)

    def __draw_name_label(self):
        screenpos = convert_3dcoor_to_screen(self.position+Vector3([self.width//2, 0, 0]))
        #draw in 2d
        set_2d_mode()
        name_length = len(self.name)
        name_text = text.Label(self.name, font_size=18, color=[0,0,0,255], x = screenpos[0], y=screenpos[1], anchor_x='center', anchor_y='bottom')

        graphics.vertex_list(4, ('v2f', (
            screenpos[0]-name_text.content_width//2-2,screenpos[1],
            screenpos[0]-name_text.content_width//2-2, screenpos[1]+25,
            screenpos[0]+name_text.content_width//2+2,screenpos[1]+25,
            screenpos[0]+name_text.content_width//2+2, screenpos[1]
        )), ('c3B', (200,200,200, 200,200,200,  200,200,200,  200,200,200))).draw(GL_QUADS)
        graphics.vertex_list(4, ('v2f', (
            screenpos[0]-name_text.content_width//2-2,screenpos[1],
            screenpos[0]-name_text.content_width//2-2, screenpos[1]+25,
            screenpos[0]+name_text.content_width//2+2,screenpos[1]+25,
            screenpos[0]+name_text.content_width//2+2, screenpos[1]
        )), ('c3B', (0,0,0, 0,0,0,  0,0,0,  0,0,0))).draw(GL_LINE_LOOP)
        name_text.draw()
        unset_2d_mode(ShapeShader.shader)

    @staticmethod
    def set_detected(garden_ids):
        for garden in Garden.instances:
            if garden in garden_ids:
                Garden.instances[garden].detected = True
            else:
                Garden.instances[garden].detected = False

    # @staticmethod
    # def unset_detected(garden_ids):
    #     for garden in garden_ids:
    #         if garden in Garden.instances:
    #             Garden.instances[garden].detected = False

    @staticmethod
    def draw_all_warning_sign():
        for garden in Garden.instances:
            if Garden.instances[garden].detected:
                Garden.instances[garden].__draw_warning_sign()

    @staticmethod
    def set_readable_to_campos(cam_pos, read_dist):
        Garden.readable_instances = []
        for garden in Garden.instances:
            grd_dist = distance_3d(cam_pos, Garden.instances[garden].position)
            if grd_dist < read_dist:
                Garden.readable_instances.append(garden)

    @staticmethod
    def draw_all_readable_names():
        set_2d_mode()
        for garden in Garden.readable_instances:
            Garden.instances[garden].__draw_name_label()
        unset_2d_mode(ShapeShader.shader)

class GardenRow:
    def __init__(self, position, max_object, obj_displacement):
        self.position = Vector3(position)
        self.row_objects = []
        self.max = max_object
        self.obj_disp = obj_displacement # a Vector3 displacement between objects

    def get_row_height(self):
        if self.row_objects == []:
            return 0
        ans = max(self.row_objects, key=lambda x: x.height).height
        return ans

    def get_row_width(self):
        if self.row_objects == []:
            return 0
        elif len(self.row_objects) == 1:
            return self.row_objects[0].width
        position = self.row_objects[-1].position - self.row_objects[0].position
        width = abs(position[0]) + self.row_objects[-1].width
        return width

    def get_next_position(self):
        if len(self.row_objects) > 0:
            prev_pos = self.row_objects[-1].position
            return prev_pos + self.obj_disp
        else:
            return self.position

    def add_square(self, new_square):
        if self.is_full():
            return False
        next_pos = self.get_next_position()
        if (next_pos != new_square.position):
            new_square.set_drawn_square(position=next_pos)
        self.row_objects.append(new_square)
        return next_pos

    def shift_row(self, vector):
        self.position += vector
        for obj in self.row_objects:
            obj.set_drawn_square(position= obj.position + vector)

    def is_full(self):
        return self.max == len(self.row_objects)<file_sep># Mushroom Farm

to use, first initialize SQL database with mushroom_farm.sql
then run main.py

When the window is loaded, you can control the camera with keyboard:
W, A, S, D for forward, left, back, right
Q and E to adjust height
T to toggle overview mode

You can see a mushroom's name by getting close
You can see a mushroom square's name by clicking it
You can see a fenced garden's name by clicking a square within it

On the GUI in the left side of the window, you can see:
The project's overall code score
A Scrollable list of code smell detection methods
A Scrollable list of changes made to the project<file_sep>#version 330
in vec2 textures;

out vec4 outColor;
uniform sampler2D sampTexture;

void main()
{
    outColor = texture(sampTexture, textures);
}
<file_sep>python main.py
ECHO "Selesai"
pause<file_sep>import pyglet
from pyglet import *
from pyglet.gl import *
from shaders import ShapeShader

# graph class
class CouplingPath:
    def __init__(self, color=[0.5,0.5,0.5,1.0] ):
        self.nodes = {}
        self.edges = []
        self.color = color
        self.datanodes = {}

    def shift_paths(self, move_vector):
        for pos in self.nodes:
            self.nodes[pos].coor += move_vector
        for edge in self.edges:
            edge.reset_shape()

    def add_node(self, coor, data=None): #create a new node and automatically connect nodes with matching coors
        if tuple(coor) in self.nodes:
            return self.nodes[tuple(coor)]
        newnode = CouplingPathNode(coor, data)
        self.nodes[tuple(coor)] = newnode
        if data is not None:
            self.datanodes[data] = newnode
        return newnode

    def add_edge(self, node1, node2): #the node1 and node2 can be node object or coordinate
        if type(node1) != CouplingPathNode:
            if tuple(node1) in self.nodes:
                node1 = self.nodes[tuple(node1)]
            else:
                node1 = self.add_node(tuple(node1))
        if type(node2) != CouplingPathNode:
            if tuple(node2) in self.nodes:
                node2 = self.nodes[tuple(node2)]
            else:
                node2 = self.add_node(tuple(node2))
        newedge = CouplingPathEdge(node1, node2)
        self.edges.append(newedge)
        return newedge

    def neighbors(self, node):
        neighbor = []
        for edge in self.edges:
            if edge.node1 == node:
                neighbor.append([edge.node2, edge])
            elif edge.node2 == node:
                neighbor.append([edge.node1, edge])
        return neighbor

    def __distance(self, coor1, coor2):
        return sum((coor1-coor2)**2)**0.5

    def search_path(self, data1, data2):
        startnode = self.datanodes[data1]
        endnode = self.datanodes[data2]
        queue = [[startnode, []]]
        possiblepaths = []
        visited = []
        while len(queue)>0:
            expand_node = queue.pop()
            if expand_node[0] == endnode:
                possiblepaths.append(expand_node[1])
            else:
                visited.append(expand_node[0])
                next_nodes = [node for node in self.neighbors(expand_node[0]) if node[0] not in visited]
                queue += [[node[0], expand_node[1]+[node[1]]] for node in next_nodes]

        try:
            return min(possiblepaths, key=lambda x: len(x))
        except: # no path found
            return []

    def draw(self, data1, data2, debug=False, direct_draw=True):
        ShapeShader.use_color(self.color)

        path = self.search_path(data1, data2)

        for edge in path:
            if direct_draw:
                edge.draw()
            else:
                if edge not in self.to_be_drawn:
                    self.to_be_drawn.append(edge)

    def draw_all_paths(self, pair_list):
        self.to_be_drawn = []
        for pair in pair_list:
            self.draw(pair[0], pair[1], direct_draw=False)
        for edge in self.to_be_drawn:
            edge.draw()

class CouplingPathNode:
    def __init__(self, coor, data=None):
        self.data = data
        self.coor = coor

class CouplingPathEdge:
    PATH_WIDTH = 4.0
    def __init__(self, node1, node2):
        self.node1 = node1
        coor1 = node1.coor
        self.node2 = node2
        coor2 = node2.coor
        if coor1[0] < coor2[0] or coor1[2] < coor2[2]:
            coor1, coor2 = coor2, coor1

        if coor1[2] != coor2[2]:
            self.set_drawn_path(coor1,coor2, True)
        else:
            self.set_drawn_path(coor1,coor2, False)

    def reset_shape(self):
        coor1 = self.node1.coor
        coor2 = self.node2.coor
        if coor1[0] < coor2[0] or coor1[2] < coor2[2]:
            coor1, coor2 = coor2, coor1

        if coor1[2] != coor2[2]:
            self.set_drawn_path(coor1,coor2, True)
        else:
            self.set_drawn_path(coor1,coor2, False)

    def set_drawn_path(self, coor1, coor2, vertical=True):
        self.coor1 = coor1
        self.coor2 = coor2
        width = CouplingPathEdge.PATH_WIDTH
        if vertical:
            self.drawn_path = graphics.vertex_list(4, ('v3f',(
                coor1[0], coor1[1], coor1[2],
                coor1[0]+width, coor1[1], coor1[2],
                coor2[0]+width, coor2[1], coor2[2]-width,
                coor2[0], coor2[1], coor2[2]-width
            )))
        else:
            self.drawn_path = graphics.vertex_list(4, ('v3f',(
                coor1[0]+width, coor1[1], coor1[2],
                coor1[0]+width, coor1[1], coor1[2]-width,
                coor2[0], coor2[1], coor2[2]-width,
                coor2[0], coor2[1], coor2[2]
            )))

    def draw(self): #draw path from node with data1 to node with data2
        self.drawn_path.draw(GL_QUADS)<file_sep>import mysql.connector as sqlcon

class DBConnector:
    DATABASE_NAME = 'mushroom_farm'

    def __init__(self, db = DATABASE_NAME):
        self.db = sqlcon.connect(
            host = 'localhost',
            user = 'root',
            passwd= '',
            database= db
        )
        self.cursor = self.db.cursor()

    def execute(self, sql):
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    def close(self):
        self.cursor.close()
        self.db.close()<file_sep>import pyglet
from pyglet import graphics
from pyglet.gl import *
from pyglet.text.formats.structured import ImageElement
from Mushrooms import *
from MushroomSquare import *
from MushroomGarden import *
from shaders import *
from DBConnector import *

class ShroomGUI:
    def __init__(self, width, height, interface_width, window, smell_score = 100, position = [0, 0], title="abcdefghijklmno"):

        self.width = width
        self.height = height

        #iw = self.cnvCoor((interface_width,0))[0]
        iw = interface_width
        self.interface_width = iw
        ih = self.height
        self.position = position
        self.fore_batch = graphics.Batch()
        self.back_batch = graphics.Batch()
        background = pyglet.graphics.OrderedGroup(0)
        foreground = pyglet.graphics.OrderedGroup(1)
        self.objectlist = []
        self.strategy_activity = []
        self.detected_shroom = {}
        self.detected_square = {}
        self.detected_garden = {}

        self.interface_box = self.back_batch.add(4, GL_QUADS, background, ('v2f',(
            position[0], position[1],
            position[0]+iw, position[1],
            position[0]+iw, position[1]+ih,
            position[0], position[1]+ih
        )), ('c4B', (
            255,255,255,255,
            255,255,255,255,
            255,255,255,255,
            255,255,255,255
        )))
        db = DBConnector()
        gui_textures = db.execute("SELECT * FROM visualpropertypath WHERE type = 'gui texture'")
        self.texture_paths = {}
        for texture in gui_textures:
            self.texture_paths[texture[1]] = texture[3]
        del db

        # project title
        self.title = pyglet.text.Label(title,
                                        font_size=17,
                                        x = position[0]+10, y=position[1]+ih-10, width = iw-20,
                                        anchor_x="left", anchor_y="top", color=(0,0,0,255),
                                        align="center", multiline=True, batch= self.fore_batch)

        #code score
        self.scoreboard = pyglet.image.load(self.texture_paths['score'])
        self.scoreboard.anchor_y = self.scoreboard.height//2
        self.scoreboard.anchor_x = self.scoreboard.width//2
        self.score_pos = (position[0]+iw//2, position[1] + ih - self.scoreboard.height//2-30-self.title.content_height)
        self.score = pyglet.text.Label("",
                                font_size = 42,
                                x = self.score_pos[0]-5, y= self.score_pos[1]+17,
                                anchor_x='center', anchor_y='center', color=(255,255,255,255), batch = self.fore_batch)
        self.set_score(smell_score)

        # making detection strategies box
        self.strategies_box = GUIBox(8, ih//2-12-iw//2-self.title.content_height, iw-16, iw+14, self.back_batch, foreground)
        strategieslabel = pyglet.text.Label ("Code Smell", font_name='Calibri',font_size=18, x=10, y = ih//2+iw//2+8-self.title.content_height, color=(0,0,0,255), batch=self.fore_batch, group=foreground)
        self.checkbox = pyglet.image.load(self.texture_paths['checkbox empty'])
        self.checkedbox = pyglet.image.load(self.texture_paths['checkbox checked'])

    def create_detection_strategies(self, strategies, detected_methods, detected_references, detected_package):
        self.detector = DetectionStrategies(strategies, detected_methods, detected_references, detected_package)
        self.init_strategies()
        for strat in strategies:
            self.add_strategies(strat[0], strat[1])
        self.finalize_strategies()

    def init_strategies(self, strategylists=[]):
        self.strategy_activity = []
        for strat in strategylists:
            self.strategy_activity.append([strat, False])

    def add_strategies(self, stratId, strategyname):
        self.strategy_activity.append([strategyname, False])

    def finalize_strategies(self):
        iw, ih = self.interface_width, self.height
        recloc = pyglet.resource.FileLocation('./')
        strat_string = "".join(["<p> <img src='{}'>{}</p>".format(self.texture_paths['checkbox empty'], x) for x,_ in self.strategy_activity])+"<br>"
        strat_doc = pyglet.text.decode_html(strat_string, location = recloc)
        self.strategies = pyglet.text.layout.IncrementalTextLayout(strat_doc, iw-20, iw+8, multiline=True, batch=self.fore_batch)
        endchar = self.strategies.get_position_on_line(self.strategies.get_line_count()-1, 999)
        #print(self.strategies.document.get_style())
        self.strategies.document.set_style(0, endchar, {'font_name':'calibri', 'font_size':15, 'line_spacing':20})
        self.strategies.x = 10
        self.strategies.y = ih//2-8-iw//2-self.title.content_height

    def set_title(self, title):
        self.title.text = title

    def set_score(self, score):
        self.score.text = str(score)

    def inside_control_box(self, x, y):
        return True ## testing

    def GUI_scroll(self, x, y, scroll_x, scroll_y):
        if self.strategies_box.is_inside(x, y):
            self.strategies.view_y += 10 * scroll_y
        # elif self.history_box.is_inside(x, y):
        #     self.log.view_y += 10 *scroll_y

    def GUI_click(self, x, y):
        if self.strategies_box.is_inside(x,y):
            #testing
            self.strategies.begin_update()
            clickedline = self.strategies.get_line_from_point(x,y)
            strategyId = clickedline + 1
            linehead = self.strategies.get_position_from_line(clickedline)
            if self.strategy_activity[clickedline][1]:
                self.strategy_activity[clickedline][1] = False
                newbox = ImageElement(self.checkbox)
            else:
                self.strategy_activity[clickedline][1] = True
                newbox = ImageElement(self.checkedbox)

            active_detectors = [id+1 for id in range(len(self.strategy_activity)) if self.strategy_activity[id][1]]
            shrooms, squares, gardens = self.detector.get_detected(active_detectors)
            Mushroom.set_detected(shrooms)
            MushroomSquare.set_detected(squares)
            Garden.set_detected(gardens)

            self.strategies.document.delete_text(linehead, linehead+1)
            self.strategies.document.insert_element(linehead, newbox)
            self.strategies.end_update()

    def draw(self):
        set_2d_mode()
        self.back_batch.draw()
        self.scoreboard.blit(*self.score_pos)
        self.fore_batch.draw()
        unset_2d_mode(ShapeShader.shader)

class GUIBox:
    def __init__(self, x, y, width, height, batch, group=None, color=[0,0,0], filled = False, drawn=True):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        if drawn:
            if filled:
                self.shape = batch.add(4, GL_QUADS, group, ('v2f', (
                    x,y, x+width,y, x+width,y+height, x,y+height
                )),('c3B', (
                    *color, *color, *color, *color
                )))
            else:
                self.shape = batch.add_indexed(4, GL_LINES, group,
                [0,1,1,2,2,3,3,0],
                ('v2f', (
                    x,y, x+width,y, x+width,y+height, x,y+height
                )), ('c3B', (
                    *color, *color, *color, *color
                )))

    def is_inside(self, x, y):
        return x > self.x and x < self.x+self.width and y > self.y and y < self.y+self.height

class DetectionStrategies:
    method_strategy = {}
    reference_strategy = {}
    package_strategy = {}

    # tabel strategies berisi kolom: ID, name, type
    # detected_object berisi object ID, strategy ID
    def __init__(self, strategies, detected_methods, detected_references, detected_packages):
        for strat in strategies:
            if strat[2] == "method":
                self.method_strategy[strat[0]] = set()
            elif strat[2] == "reference":
                self.reference_strategy[strat[0]] = set()
            else:
                self.package_strategy[strat[0]] = set()
        for det in detected_methods:
            self.method_strategy[det[1]].add('m'+str(det[0]))
        for det in detected_references:
            self.reference_strategy[det[1]].add(det[0])
        for det in detected_packages:
            self.package_strategy[det[1]].add(det[0])

    def get_detected(self, strategy_id_list):
        detected_methods = []
        detected_references = []
        detected_packages = []

        for strat_id in strategy_id_list:
            if strat_id in self.method_strategy:
                detected_methods.append(self.method_strategy[strat_id])
            elif strat_id in self.reference_strategy:
                detected_references.append(self.reference_strategy[strat_id])
            elif strat_id in self.package_strategy:
                detected_packages.append(self.package_strategy[strat_id])

        if detected_methods:
            detected_methods = list(detected_methods[0].intersection(*detected_methods[1:]))
        if detected_references:
            detected_references = list(detected_references[0].intersection(*detected_references[1:]))
        if detected_packages:
            detected_packages = list(detected_packages[0].intersection(*detected_packages[1:]))

        return detected_methods, detected_references, detected_packages
<file_sep>from pyglet.gl import *
from pyglet import graphics
from pyglet import gl
from pyglet import clock
from pyglet.window import key
import ShaderLoader
from ObjLoader import ObjLoader
from pyrr import Vector3, Vector4, matrix44, Matrix44
from shaders import *
import time
import numpy
import random
from DBConnector import *
import threading

class Mushroom:
    instances = {}
    instance_locations = {}
    instance_info = {}
    readable_instances = []
    detected = []
    db = DBConnector()
    shroom_paths = db.execute("SELECT path FROM visualpropertypath WHERE path LIKE '%Mushroom.obj'")
    shroom_paths = sorted([x[0] for x in shroom_paths], reverse=True) #now, list will be sorted small-medium-large
    del db
    texture_offsets = []
    data_list = []
    for i in range(3):
        mesh = ObjLoader()
        mesh.load_model(shroom_paths[i])
        num_verts = len(mesh.vertex_index)
        texture_offset = len(mesh.vertex_index) * 12
        data = numpy.array(mesh.model, dtype=GLfloat)
        texture_offsets.append(texture_offset)
        data_list.append(data)

    def __init__(self, tekstur, code, size=0):
        code += str(size)
        if code in Mushroom.instances:
            return None
        Mushroom.instances[code] = self
        Mushroom.instance_locations[code] = []

        self.vao_mushroom = GLuint()
        # generate a vertex array object for the mushroom - the vao
        glGenVertexArrays(1, self.vao_mushroom)
        # bind the mushroom's vao
        glBindVertexArray(self.vao_mushroom)
        # setup the mushroom's vertex buffer object - the vbo
        vbo_sphere = pyglet.graphics.vertexbuffer.create_buffer(Mushroom.data_list[size].nbytes, GL_ARRAY_BUFFER, GL_STATIC_DRAW)
        vbo_sphere.bind()
        vbo_sphere.set_data(Mushroom.data_list[size].ctypes.data)

        # vertex attribute pointer settings for the mushroom vbo
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0)
        glEnableVertexAttribArray(0)

        # textures
        glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, Mushroom.texture_offsets[size])
        glEnableVertexAttribArray(1)

        glBindBuffer(GL_ARRAY_BUFFER, 0)  # unbind the vbo
        glBindVertexArray(0)  # unbind the vao

        # region texture settings
        self.texture = GLuint(0)
        glGenTextures(1, self.texture)
        glBindTexture(GL_TEXTURE_2D, self.texture)
        # set the texture wrapping
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
        # set the texture filtering
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)

        # self.loadingthread = GeneralThread(load_texture_image, self, tekstur)
        # self.loadingthread.run()

        image = pyglet.image.load(tekstur)

        image_data = image.get_data('RGB', image.pitch)

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data)

        # endregion

    def render(self, translasi):
        # if self.loadingthread.isAlive():
        #     return
        # to draw the mushroom, we need to rebind the mushroom's vao

        model_loc = ObjectShader.model_loc
        mushroom_model = matrix44.create_from_translation(translasi).flatten().astype("float32") #this is the model transformation matrix
        c_mushroom_model = numpy.ctypeslib.as_ctypes(mushroom_model)

        glBindVertexArray(self.vao_mushroom)
        glBindTexture(GL_TEXTURE_2D, self.texture)
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, c_mushroom_model)
        glDrawArrays(GL_TRIANGLES, 0, Mushroom.num_verts)
        glBindVertexArray(0)

    def batch_render(self, list_translasi, undraw_detected=False): # me-render banyak mushroom dengan tekstur sama
        # if self.loadingthread.isAlive():
        #     return
        glBindVertexArray(self.vao_mushroom)
        glBindTexture(GL_TEXTURE_2D, self.texture)
        model_loc = ObjectShader.model_loc
        detected_translasi = [Mushroom.instance_info[x][2] for x in Mushroom.detected]

        for translasi in list_translasi:
            if translasi not in detected_translasi or not undraw_detected:
                mushroom_model = matrix44.create_from_translation(Vector3(translasi)).flatten().astype("float32") #this is the model transformation matrix
                c_mushroom_model = numpy.ctypeslib.as_ctypes(mushroom_model)
                glUniformMatrix4fv(model_loc, 1, GL_FALSE, c_mushroom_model)
                glDrawArrays(GL_TRIANGLES, 0, Mushroom.num_verts)
        glBindVertexArray(0)

    @staticmethod
    def _draw_name_label(name, position):
        screenpos = convert_3dcoor_to_screen(position)
        # set_2d_mode()
        name_text = text.Label(name, font_size=18, color=[0,0,0,255], x = screenpos[0], y=screenpos[1], anchor_x='center', anchor_y='bottom')

        name_length = (name_text.content_width+5)/2
        graphics.vertex_list(4, ('v2f', (
            screenpos[0]-name_length,screenpos[1],
            screenpos[0]-name_length, screenpos[1]+25,
            screenpos[0]+name_length,screenpos[1]+25,
            screenpos[0]+name_length, screenpos[1]
        )), ('c3B', (200,200,200, 200,200,200,  200,200,200,  200,200,200))).draw(GL_QUADS)
        graphics.vertex_list(4, ('v2f', (
            screenpos[0]-name_length,screenpos[1],
            screenpos[0]-name_length, screenpos[1]+25,
            screenpos[0]+name_length,screenpos[1]+25,
            screenpos[0]+name_length, screenpos[1]
        )), ('c3B', (0,0,0, 0,0,0,  0,0,0,  0,0,0))).draw(GL_LINE_LOOP)
        name_text.draw()
        # unset_2d_mode(ShapeShader.shader)

    @staticmethod
    def draw_warning_sign(position):
        screenpos = convert_3dcoor_to_screen(position)
        screenpos[0] -= 18
        screenpos[1] += 36
        # draw in 2d
        # set_2d_mode()
        graphics.vertex_list(3, ('v2f', (
            screenpos[0], screenpos[1],
            screenpos[0]+36, screenpos[1],
            screenpos[0]+18, screenpos[1]+36
        )), ('c3B', (
            255,255,0, 255,255,0, 255,255,0
        ))).draw(GL_TRIANGLES)
        text.Label('!', font_size=18, color=[0,0,0,255], x=screenpos[0]+14, y=screenpos[1], anchor_x='left', anchor_y='bottom').draw()
        # unset_2d_mode(ShapeShader.shader)

    @staticmethod
    def get_all_shroom_position():
        shroom_list = []
        for key in Mushroom.instance_locations:
            shroom_list += Mushroom.instance_locations[key]
        return shroom_list

    @staticmethod
    def add_instance_location(shroomtype, location):
        Mushroom.instance_locations[shroomtype].append(location)

    @staticmethod
    def add_instance_detail(shroom_id, name, shroomtype, location, is_field):
        if is_field:
            used_id = 'f'+str(shroom_id)
            Mushroom.instance_info[used_id] = [name, shroomtype, location]
        else:
            used_id = 'm'+str(shroom_id)
            Mushroom.instance_info[used_id] = [name, shroomtype, location]
        Mushroom.add_instance_location(shroomtype, location)

    @staticmethod
    def move_shroom(shroom_id, is_field, shift_vector):
        used_id = ('f' if is_field else 'm') + str(shroom_id)
        Mushroom.instance_info[used_id][2] += shift_vector

    @staticmethod
    def set_readable(shroom_pos_list):
        Mushroom.readable_instances = shroom_pos_list

    @staticmethod
    def add_detected(shroom_ids):
        Mushroom.detected += [shroom for shroom in shroom_ids if shroom not in Mushroom.detected]

    @staticmethod
    def remove_detected(shroom_ids):
        Mushroom.detected = [shroom for shroom in Mushroom.detected if shroom not in shroom_ids]

    @staticmethod
    def set_detected(shroom_ids):
        Mushroom.detected = shroom_ids

    @staticmethod
    def draw_all_shroom(undraw_detected=False):
        for key in Mushroom.instances:
            Mushroom.instances[key].batch_render(Mushroom.instance_locations[key], undraw_detected=undraw_detected)
        set_2d_mode()
        for shroom_pos in Mushroom.readable_instances:
            all_info = Mushroom.instance_info.items()
            for info in all_info:
                if info[1][2] == shroom_pos:
                    Mushroom._draw_name_label(info[1][0], info[1][2])
        # for warned_id in Mushroom.detected:
        #     Mushroom.draw_warning_sign(Mushroom.instance_info[warned_id][2])
        unset_2d_mode(ObjectShader.shader)

languages: Java Markdown SQL Batchfile Python GLSL

repo_language: Java

repo_name: anandhininababan/codevis-mushroomfarm